详解Java发送HTTP请求
前言
请求http的Demo是个人亲测过,目前该方式已经在线上运行着。因为是http请求,所有发送post和get请求的demo都有在下方贴出,包括怎么测试,大家可直接copy到自己的项目中使用。
正文
使用须知
为了避免大家引错包我把依赖和涉及到包路径给大家
importjava.net.HttpURLConnection; importjava.net.URI; importorg.apache.http.HttpResponse; importorg.apache.http.HttpStatus; importorg.apache.http.client.methods.HttpGet; importorg.apache.http.client.methods.HttpPost; importorg.apache.http.client.utils.URIBuilder; importorg.apache.http.entity.StringEntity; importorg.apache.http.impl.client.CloseableHttpClient; importorg.apache.http.impl.client.DefaultHttpClient; importorg.apache.http.impl.client.HttpClients; importorg.apache.http.util.EntityUtils; importcom.fasterxml.jackson.databind.ObjectMapper;
org.apache.httpcomponents httpcore 4.4.8 org.apache.httpcomponents httpclient 4.5.3
HTTP发送get请求
首先我们引入两个包
发送get请求的工具类,可直接copy使用即可
另外,我抛出异常的代码大家改成自己业务的异常,不需要就删除掉。
参数说明:
host:ip
servUri:url
reString:参数
publicstaticStringgetHttpData(Stringhost,StringservUri,StringreString)throwsException{ StringBuffersb=newStringBuffer(); sb.append("getHttpData:host:"+host+",servUri:"+servUri+",reString:"+reString); StringstrResp=null; try{ URIuri=newURIBuilder().setScheme("http").setHost(host).setPath(servUri) .setParameter("strInfo",reString).build(); HttpGethttpGet=newHttpGet(uri); CloseableHttpClientclient3=HttpClients.createDefault(); HttpResponseresp; resp=client3.execute(httpGet); if(resp.getStatusLine().getStatusCode()==HttpURLConnection.HTTP_OK){ strResp=EntityUtils.toString(resp.getEntity()); logger.info("thereturnresult:{}",strResp); }else{ logger.info("ErrorResponse:",resp.getStatusLine().toString()); thrownewCommonBusinessException(CommonConstants.TASK_RELEASE_WCF, CommonConstants.TASK_RELEASE_WCF_DESC); } }catch(Exceptione){ logger.error(sb.toString()+":"+e.getMessage(),e.getCause()); thrownewCommonBusinessException(CommonConstants.TASK_RELEASE_WCF,CommonConstants.TASK_RELEASE_WCF_DESC); } returnstrResp; }
HTTP发送post请求
发送post分两种,我分两种的原因是为了让大家方便,想传对象和json可以直接复制过用就可以用,不用你们在转了。
第一种是直接接收json
参数明说:
url:url
json:参数
publicstaticStringdoPostData(Stringurl,Stringjson)throwsException{ DefaultHttpClientclient=newDefaultHttpClient(); HttpPostpost=newHttpPost(url); Stringresult=""; HttpResponseres=null; try{ StringEntitys=newStringEntity(json.toString(),"UTF-8"); s.setContentType("application/json"); post.setHeader("Accept","application/json"); post.setHeader("Content-type","application/json;charset=utf-8"); post.setEntity(s); res=client.execute(post); if(res.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ result=EntityUtils.toString(res.getEntity()); returnHttpStatus.SC_OK+""; } }catch(Exceptione){ if(res==null){ return"HttpResponse为null!"; } thrownewRuntimeException(e); } if(res==null||res.getStatusLine()==null){ return"无响应"; } returnres.getStatusLine().getStatusCode()+""; }
@Test publicvoidtest12()throwsException{ StringHOST="http://eipwcf.aspirecn.com/SvcEF/Service1.svc/WCF_EF_MSA_GetDataInfo_P"; HttpClientclient=newHttpClient(); JSONObjectjson=newJSONObject(); json.put("msgId",msgId); Stringreslut=client.doPostData(HOST,json); }
第二种是参数是对象
参数说明:
url:url
tram:对象
publicstaticStringdoHttpPostData(Stringurl,TaskReleaseApprovalModeltram) throwsException{ StringBuffersb=newStringBuffer(); sb.append("doHttpPostData:url:"+url+",tram:"+tram.toString()+",contentType:"+contentType); logger.info(sb.toString()); StringtmpString=""; HttpPostrequest=newHttpPost(url); request.setHeader("Accept","application/json"); request.setHeader("Content-type","application/json"); ObjectMappermapper=newObjectMapper(); StringjsonString; try{ jsonString=mapper.writeValueAsString(tram); StringEntityentity=newStringEntity(jsonString,"UTF-8"); request.setEntity(entity); CloseableHttpClientclient=HttpClients.createDefault(); HttpResponseresponse=client.execute(request); if(response.getStatusLine().getStatusCode()==HttpURLConnection.HTTP_OK){ tmpString=EntityUtils.toString(response.getEntity()); logger.info("thepostresult:tmpString:{}",tmpString); }else{ logger.info("thepostfailure:tmpString:",tmpString); thrownewCommonBusinessException(CommonConstants.TASK_RELEASE_WCF, CommonConstants.TASK_RELEASE_WCF_DESC); } }catch(Exceptione){ logger.error(sb.toString()+":"+e.getMessage(),e.getCause()); thrownewCommonBusinessException(CommonConstants.TASK_RELEASE_POSTWCF, CommonConstants.TASK_RELEASE_POSTWCF_DESC); } returntmpString; }
这个方法我想不用写测试类大家也会用,传过去对象和地址就可以了,很方便很简单。
以上所述是小编给大家介绍的Java发送HTTP请求详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!