Java httpcomponents发送get post请求代码实例
引入的包为:
org.apache.httpcomponents httpclient 4.5.8
实现的工具类为:
importcom.alibaba.fastjson.JSON; importorg.apache.http.NameValuePair; importorg.apache.http.client.entity.UrlEncodedFormEntity; importorg.apache.http.client.methods.CloseableHttpResponse; importorg.apache.http.client.methods.HttpGet; importorg.apache.http.client.methods.HttpPost; importorg.apache.http.impl.client.CloseableHttpClient; importorg.apache.http.impl.client.HttpClients; importorg.apache.http.message.BasicNameValuePair; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importjava.io.IOException; importjava.util.ArrayList; importjava.util.HashMap; importjava.util.List; importjava.util.Map; publicclassHttpClientHelper{ privatestaticLoggerlogger=LoggerFactory.getLogger(HttpClientHelper.class); privateHttpClientHelper(){ } /** *发起POST请求 * *@paramurlurl *@paramparamMap参数的Map格式 */ publicstaticvoidsendPost(Stringurl,MapparamMap){ logger.info("开始发起POST请求,请求地址为{},参数为{}",url,JSON.toJSON(paramMap)); CloseableHttpResponseresponse=null; try(CloseableHttpClienthttpClient=HttpClients.createDefault()){ Stringencoding="utf-8"; //创建post请求对象 HttpPosthttpPost=newHttpPost(url); //装填请求参数 List list=newArrayList<>(); for(Map.Entry entry:paramMap.entrySet()){ list.add(newBasicNameValuePair(entry.getKey(),entry.getValue())); } //设置参数到请求对象中 httpPost.setEntity(newUrlEncodedFormEntity(list,encoding)); httpPost.setHeader("Content-type","application/x-www-form-urlencoded"); httpPost.setHeader("User-Agent","Mozilla/4.0(compatible;MSIE5.0;WindowsNT;DigExt)"); response=httpClient.execute(httpPost); }catch(IOExceptione){ logger.error("POST请求发出失败,请求的地址为{},参数为{},错误信息为{}",url,JSON.toJSON(paramMap),e.getMessage(),e); }finally{ try{ if(response!=null){ response.close(); } }catch(IOExceptione){ logger.error("POST请求response关闭异常,错误信息为{}",e.getMessage(),e); } } } /** *发起GET请求 * *@paramurlParamurl请求,包含参数 */ publicstaticvoidsendGet(StringurlParam){ logger.info("开始发起GET请求,请求地址为{}",urlParam); HttpGethttpGet=newHttpGet(urlParam); CloseableHttpResponseresponse=null; try(CloseableHttpClienthttpClient=HttpClients.createDefault()){ response=httpClient.execute(httpGet); intstatus=response.getStatusLine().getStatusCode(); logger.error("GET请求发出成功,请求的地址为{},返回状态为{}",urlParam,status); }catch(IOExceptione){ logger.error("GET请求发出失败,请求的地址为{},错误信息为{}",urlParam,e.getMessage(),e); }finally{ try{ if(response!=null){ response.close(); } }catch(IOExceptione){ logger.error("GET请求response关闭异常,错误信息为{}",e.getMessage(),e); } } } publicstaticvoidmain(String[]args){ Stringurl="https://jiashubing.cn/tencenttest"; //需要传入的参数 Map map=newHashMap<>(); map.put("code","js"); map.put("day","0"); map.put("city","北京"); map.put("dfc","1"); map.put("charset","utf-8"); sendPost(url,map); StringurlParam="https://jiashubing.cn/talk/document?fileid=1234ji贾树丙"; sendGet(urlParam); } }
如果POST请求想要发送Json格式的数据,只需要修改成这样:
Stringjson=JSON.toJSONString(paramMap);
StringEntityrequestEntity=newStringEntity(json,"utf-8");
httpPost.setEntity(requestEntity);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。