maven
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.9</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
java代码
package com.fhlh.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 发送http请求工具类
*/
public class HttpUtils {
/**
* http的post请求带有json的请求体
* @param url
* @param json
* @return
*/
public static StringHttpPostWithJson(String url, String json) {
long start = System.currentTimeMillis();
String returnValue =”这是默认返回值,接口调用失败”;
CloseableHttpClient httpClient = HttpClients.createDefault();
ResponseHandler responseHandler =new BasicResponseHandler();
try{
//第一步:创建HttpClient对象
httpClient = HttpClients.createDefault();
//第二步:创建httpPost对象
HttpPost httpPost =new HttpPost(url);
//第三步:给httpPost设置JSON格式的参数
StringEntity requestEntity =new StringEntity(json,”utf-8″);
requestEntity.setContentEncoding(“UTF-8”);
httpPost.setHeader(“Content-type”, “application/json”);
httpPost.setEntity(requestEntity);
//第四步:发送HttpPost请求,获取返回值
returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时,必须用此方法
httpClient.close();
}
catch(Exception e)
{
e.printStackTrace();
}finally {
try {
httpClient.close();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
long end = System.currentTimeMillis();
System.out.println(“time:”+(end-start));
//第五步:处理返回值
return returnValue;
}
/**
* http的post请求带有json的请求体
* @param url
* @param json
* @return
*/
public static StringHttpPostWithJsonAndHead(String url, String token, String json) {
long start = System.currentTimeMillis();
String returnValue =”这是默认返回值,接口调用失败”;
CloseableHttpClient httpClient = HttpClients.createDefault();
ResponseHandler responseHandler =new BasicResponseHandler();
try{
//第一步:创建HttpClient对象
httpClient = HttpClients.createDefault();
//第二步:创建httpPost对象
HttpPost httpPost =new HttpPost(url);
//第三步:给httpPost设置JSON格式的参数
if(json !=null) {
StringEntity requestEntity =new StringEntity(json, “utf-8”);
requestEntity.setContentEncoding(“UTF-8”);
httpPost.setEntity(requestEntity);
}
httpPost.setHeader(“Content-type”, “application/json”);
httpPost.setHeader(“token”, token);
//第四步:发送HttpPost请求,获取返回值
returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时,必须用此方法
httpClient.close();
}
catch(Exception e)
{
e.printStackTrace();
}finally {
try {
httpClient.close();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
long end = System.currentTimeMillis();
System.out.println(“time:”+(end-start));
//第五步:处理返回值
return returnValue;
}
/**
* get请求,参数放在map里
* @param url 请求地址
* @param map 参数map
* @return 响应
*/
public StringgetMap(String url, Map map)
{
String result =null;
CloseableHttpClient httpClient = HttpClients.createDefault();
List pairs =new ArrayList();
if(map !=null) {
for (Map.Entry entry : map.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
CloseableHttpResponse response =null;
try {
URIBuilder builder =new URIBuilder(url);
builder.setParameters(pairs);
HttpGet get =new HttpGet(builder.build());
response = httpClient.execute(get);
if(response !=null && response.getStatusLine().getStatusCode() ==200)
{
HttpEntity entity = response.getEntity();
result =entityToString(entity);
}
return result;
}catch (URISyntaxException e) {
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response !=null)
{
response.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static StringgetMapWithHeader(String url, String token, Map map)
{
String result =null;
CloseableHttpClient httpClient = HttpClients.createDefault();
List pairs =new ArrayList();
if(map !=null) {
for (Map.Entry entry : map.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
CloseableHttpResponse response =null;
try {
URIBuilder builder =new URIBuilder(url);
builder.setParameters(pairs);
HttpGet get =new HttpGet(builder.build());
get.addHeader(“token”, token);
response = httpClient.execute(get);
if(response !=null && response.getStatusLine().getStatusCode() ==200)
{
HttpEntity entity = response.getEntity();
result =entityToString(entity);
}
return result;
}catch (URISyntaxException e) {
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response !=null)
{
response.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
private static StringentityToString(HttpEntity entity)throws IOException {
String result =null;
if(entity !=null)
{
long lenth = entity.getContentLength();
if(lenth != -1 && lenth <2048)
{
result = EntityUtils.toString(entity,”UTF-8″);
}else {
InputStreamReader reader1 =new InputStreamReader(entity.getContent(), “UTF-8”);
CharArrayBuffer buffer =new CharArrayBuffer(2048);
char[] tmp =new char[1024];
int l;
while((l = reader1.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
result = buffer.toString();
}
}
return result;
}
/**
* 发送post请求,参数用map接收
* @param url 地址
* @param map 参数
* @return 返回值
*/
public StringpostMap(String url,Map map) {
String result =null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post =new HttpPost(url);
List pairs =new ArrayList();
for(Map.Entry entry : map.entrySet())
{
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
CloseableHttpResponse response =null;
try {
post.setEntity(new UrlEncodedFormEntity(pairs,”UTF-8″));
response = httpClient.execute(post);
if(response !=null && response.getStatusLine().getStatusCode() ==200)
{
HttpEntity entity = response.getEntity();
result =entityToString(entity);
}
return result;
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
if(response !=null)
{
response.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static StringhttpGet(String url)throws Exception{
String result=””; //返回信息
//创建一个httpGet请求
HttpGet request=new HttpGet(url);
//创建一个htt客户端
HttpClient httpClient=new DefaultHttpClient();
//接受客户端发回的响应
HttpResponse httpResponse=httpClient.execute(request);
//获取返回状态
int statusCode=httpResponse.getStatusLine().getStatusCode();
if(statusCode== HttpStatus.SC_OK){
//得到客户段响应的实体内容
HttpEntity responseHttpEntity=httpResponse.getEntity();
//得到输入流
InputStream in=responseHttpEntity.getContent();
//得到输入流的内容
result=getData(in);
}
//Log.d(TAG, statusCode+””);
return result;
}
private static StringgetData(InputStream in)throws IOException {
StringBuffer sb =new StringBuffer();
byte[] b =new byte[1024];
int len = -1;
while((len = in.read(b)) != -1){
sb.append(new String(b, 0, len));
}
return sb.toString();
}
public static void main(String[] args)throws Exception {
System.out.println(httpGet(“https://api.inews.qq.com/newsqa/v1/query/inner/publish/modules/list?modules=statisGradeCityDetail,diseaseh5Shelf”));
}
}