1.下载apache client项目jar包 http://mirrors.tuna.tsinghua.edu.cn/apache//httpcomponents/httpclient/binary/httpcomponents-client-4.5.3-bin.tar.gz
httpcomponents-client-4.5.3lib 下面的jar包
package com.service;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.*;
public class ApacheHttpClientUtil {
/**
* 发送post请求
*
* @param url
* @param parameters
*/
public static void httpPost(String url, Map<String, String> parameters) {
CloseableHttpClient httpclient = null;
CloseableHttpResponse response = null;
try {
httpclient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
// post 参数 传递
if (parameters != null) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> map : parameters.entrySet()) {
String key = map.getKey().toString();
String value = map.getValue().toString();
list.add(new BasicNameValuePair(key, value));
}
post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
}
response = httpclient.execute(post);
// 请求发送成功,并得到响应
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//读取服务器返回过来的json字符串数据
String strResult = EntityUtils.toString(response.getEntity());
System.out.println(strResult);
} else {
System.out.println("请求失败");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
if (httpclient != null) {
httpclient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void httpGet(String url) {
CloseableHttpClient httpclient = null;
CloseableHttpResponse response = null;
try {
//发送get请求
httpclient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
response = httpclient.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
String strResult = EntityUtils.toString(response.getEntity());
System.out.println(strResult);
} else {
System.out.println("请求失败");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
if (httpclient != null) {
httpclient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}