关于java:86MyHttpClientThird

36次阅读

共计 1906 个字符,预计需要花费 5 分钟才能阅读完成。

package com.homlin.module.qyapi.utils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.IOException;
/**
* super_dev_007 2020/11/22
*/
public class MyHttpClientThird {
/**
* 发动 POST 申请
*
* @param url url
* @param paramJson 参数的 json 格局
*/
public static String sendPost(String url, String paramJson) {
// 创立 httpClient 实例对象
HttpClient httpClient = new HttpClient();
// 设置 httpClient 连贯主机服务器超时工夫:15000 毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 创立 post 申请办法实例对象
PostMethod postMethod = new PostMethod(url);
// 设置 post 申请超时工夫
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
postMethod.addRequestHeader("Content-Type", "application/json");
try {
//json 格局的参数解析
RequestEntity entity = new StringRequestEntity(paramJson, "application/json", "UTF-8");
postMethod.setRequestEntity(entity);
httpClient.executeMethod(postMethod);
String result = postMethod.getResponseBodyAsString();
postMethod.releaseConnection();
return result;
} catch (IOException e) {e.printStackTrace();
}
return null;
}
/**
* 发动 GET 申请
*
* @param urlParam url 申请,蕴含参数
*/
public static String sendGet(String urlParam) {
// 创立 httpClient 实例对象
HttpClient httpClient = new HttpClient();
// 设置 httpClient 连贯主机服务器超时工夫:15000 毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 创立 GET 申请办法实例对象
GetMethod getMethod = new GetMethod(urlParam);
// 设置 post 申请超时工夫
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
getMethod.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
try {httpClient.executeMethod(getMethod);
String result = getMethod.getResponseBodyAsString();
getMethod.releaseConnection();
return result;
} catch (IOException e) {e.printStackTrace();
}
return null;
}
}

正文完
 0