HttpClient两种调用方式

一.参数字符串

/**
* HttpClient请求接口
* @return 成功:音频字节 失败:null
*/
public static byte[] requestBaiduAudio(String url,Map<String, String> parameter) {

PostMethod post = null;
try {
HttpClient client = new HttpClient();

// 连接超时:10秒
client.getHttpConnectionManager().getParams().setConnectionTimeout(10 * 1000);

// 读取超时:10 秒
client.getHttpConnectionManager().getParams().setSoTimeout(10 * 1000);

post = new PostMethod(url);
post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");// 在头文件中设置转码
post.setRequestHeader("Connection", "close");

NameValuePair[] data = new NameValuePair[parameter.size()];
Object s[] = parameter.keySet().toArray();
for (int i = 0; i < parameter.size(); i++) {
NameValuePair namevalue = new NameValuePair(s[i].toString(), parameter.get(s[i]));
data[i] = namevalue;
}

post.setRequestBody(data);

//发送请求
client.executeMethod(post);

//返回结果
byte[] responseBody = null;
Header contentType = post.getResponseHeader("Content-Type");
if(contentType.getValue().contains("audio/")){
responseBody = post.getResponseBody();
}else {
System.err.println("ERROR: content-type= " + contentType);
String res = post.getResponseBodyAsString();
System.err.println(res);
}

post.releaseConnection();// 释放链接

return responseBody;
} catch (Exception e) {
if (post != null)
post.releaseConnection();// 释放链接
}
return null;
}

二,参数为json

/**
* HttpClient Json 请求接口
* @return json
*/
public static JSONObject request(String url,JSONObject json) {
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(8 * 1000) //设置连接超时时间,单位毫秒
.setSocketTimeout(8 * 1000) //请求获取数据的超时时间,单位毫秒
.build();
CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
HttpPost post = new HttpPost(url);
StringEntity params = new StringEntity(json.toString(), "utf-8");
params.setContentType("text/html;charset=UTF-8");
params.setContentEncoding("UTF-8");
post.setEntity(params);
JSONObject response = null;
try {
HttpResponse res = httpclient.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = JSONObject.parseObject(result);
}else{
System.out.println(res.getStatusLine().getStatusCode());
}

} catch (Exception e) {
e.printStackTrace();
}

return response;
}

需要jar包: httpcore-4.4.10.jar,httpclient-4.5.2.jar,commons-httpclient-3.0.1.jar,commons-codec-1.9.jar

猜你喜欢

转载自www.cnblogs.com/yangyang2018/p/10234208.html