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

httpclient 调用接口工具抽取

2018-06-03 14:59 295 查看
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientMyUtil {

/**
* 发送有参数的get的请求
* @param url 
* @param params 请求参数
* @return
*/
public static String get(String url,Map<String , String > params){
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
URIBuilder builder = new URIBuilder(url);
if(params !=null && params.size()>0){
for(Entry<String , String > param : params.entrySet()){
builder.addParameter(param.getKey(), param.getValue());
}
}
HttpGet httpGet = new HttpGet(builder.build());

CloseableHttpResponse response = httpClient.execute(httpGet);

if(response.getStatusLine().getStatusCode() == 200){
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
*无参数的get的请求
* @param url
* @return
*/
public static String get(String url){

return get(url,null);
}

/**
* 带参数的post的请求
* @param url
* @param params
* @return
*/
public static String  post(String url,Map<String , String > params){
CloseableHttpClient httpClient = HttpClients.createDefault();
//构建http post请求
HttpPost post = new HttpPost(url);
try {
UrlEncodedFormEntity from = null;
if(params != null && params.size()>0){
List<NameValuePair> nValuePairs = new ArrayList<NameValuePair>();
for(Entry<String , String > entry : params.entrySet()){
nValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
from = new UrlEncodedFormEntity(nValuePairs,"utf-8");
post.setEntity(from);
}
//发送请求
CloseableHttpResponse execute =  httpClient.execute(post);
//获得响应结果
HttpEntity entity = execute.getEntity();
//解析响应结果
return EntityUtils.toString(entity,"utf-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

/**
* 调用此方法及有可能使用的此段代码
* String json = "";//httpclient 调用接口返回的json数据
Gson gson = new Gson();
//通过Gson将json数据封装到list的集合里(集合里装的是Goods实体类)
List<Goods> goods = gson.fromJson(json, new TypeToken<List<Goods>>(){}.getType());
*/
}

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: