HttpClient发送GET和POST实例

/**
 * HttpClient 模拟发送http请求
 * @author zxl
 * @date   2018年6月18日上午9:28:41
 * @描述:
 *
 */
public class HttpClientUtil {

/**
* GET请求
* @param url
* @param params
* @return String
*/
public static String doGet(String url,List<NameValuePair> params){
CloseableHttpClient client=HttpClients.createDefault();
try {
String param=EntityUtils.toString(new UrlEncodedFormEntity(params,Consts.UTF_8));
HttpGet httpGet=new HttpGet(url+"?"+param);
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
HttpResponse response=client.execute(httpGet);
System.out.println("statusCode:"+response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
HttpEntity httpEntity=response.getEntity();
String res=EntityUtils.toString(httpEntity, "utf-8");
return res;
}
} catch (ParseException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;

}

/**
* POST请求
* @param url
* @param jsonObject
* @return JSONObject
*/
public static JSONObject doPost(String url,JSONObject jsonObject) {
CloseableHttpClient client=HttpClients.createDefault();
HttpPost httpPost=new HttpPost(url);
System.out.println("jsonObject:"+jsonObject.toString());
StringEntity entity=new StringEntity(jsonObject.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
//设置User-Agent,否则请求码403
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
httpPost.setEntity(entity);
HttpResponse httpResponse = null;
try {
httpResponse = client.execute(httpPost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int resultCode=httpResponse.getStatusLine().getStatusCode();
System.out.println("resultCode:"+resultCode);
if(resultCode==200) {
HttpEntity entity2=httpResponse.getEntity();
try {
String result=EntityUtils.toString(entity2, "utf-8");
return JSONObject.parseObject(result);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
return null;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值