您的位置:首页 > 理论基础 > 计算机网络

HttpClient 发送GET和POST请求(HTTP)

2016-12-03 16:53 591 查看

1、导入相关的包:

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
<classifier>sources</classifier>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>


2、贴代码:

package cn.test.util;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtils {
/**
* 发送 GET 请求(HTTP),K-V形式
* @param url
*            不带参数的url
* @param map
*            请求参数
* @return
*/
public static String doGet(String url, Map<String, Object> map) {
String result = null;
// 拼接url
String modelUrl = url;
int i = 0;
StringBuilder param = new StringBuilder();
for (Entry<String, Object> entry : map.entrySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(entry.getKey()).append("=").append(entry.getValue());
i++;
}
modelUrl += param;
//创建HttpClient实例
HttpClient httpClient = HttpClients.createDefault();
try {
//创建HttpGet实例
HttpGet httpGet = new HttpGet(modelUrl);
//执行execute()方法,返回HttpResponse
HttpResponse response = httpClient.execute(httpGet);
//获取HttpEntity对象,该对象包装了服务器的响应内容
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
result = IOUtils.toString(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}

/**
* 发送 POST 请求(HTTP),K-V形式
* @param url
*            API接口URL
* @param map
*            参数
* @return
*/
public static String doPost(String url, Map<String, Object> map) {
String result = null;
//创建默认的HttpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
//创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
try {
//创建参数列队
List<NameValuePair> pairList = new ArrayList<>(map.size());
for (Map.Entry<String, Object> entry : map.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
//执行execute()方法
response = httpClient.execute(httpPost);
//获取HttpEntity对象
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
//关闭HttpEntity的流
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}

/**
* 发送 POST 请求(HTTP),JSON形式
* @param url
* @param json
*            json对象
* @return
*/
public static String doPost(String url, Object json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = null;
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;

try {
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");

af1f
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
result = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result ;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JAVA HTTP HttpClient