包com.taotao.common.utils;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientUtils {
public static String doGet(String url,Map <String,String> paramMap){
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = null;
try {
// 1.创建httpClient对象
httpClient = HttpClients.createDefault();
//2.创建URI
URIBuilder uriBuilder = new URIBuilder(url);
if(paramMap != null && !paramMap.isEmpty()) {
for(String key : paramMap.keySet()) {
uriBuilder.addParameter(key, paramMap.get(key));
}
}
URI uri = uriBuilder.build();
//3.创建HttpGet
HttpGet httpGet = new HttpGet(uri);
//4.发送http请求
response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity(),"utf-8");
//5.获取响应结果
if(response != null && response.getStatusLine().getStatusCode() == 200) {
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(httpClient != null) {
httpClient.close();
}
if(response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientUtils {
public static String doGet(String url,Map <String,String> paramMap){
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = null;
try {
// 1.创建httpClient对象
httpClient = HttpClients.createDefault();
//2.创建URI
URIBuilder uriBuilder = new URIBuilder(url);
if(paramMap != null && !paramMap.isEmpty()) {
for(String key : paramMap.keySet()) {
uriBuilder.addParameter(key, paramMap.get(key));
}
}
URI uri = uriBuilder.build();
//3.创建HttpGet
HttpGet httpGet = new HttpGet(uri);
//4.发送http请求
response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity(),"utf-8");
//5.获取响应结果
if(response != null && response.getStatusLine().getStatusCode() == 200) {
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(httpClient != null) {
httpClient.close();
}
if(response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
测试