重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这篇文章给大家介绍Java中怎么发送HTTP请求,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
站在用户的角度思考问题,与客户深入沟通,找到安乡网站设计与安乡网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:成都网站制作、成都网站设计、外贸营销网站建设、企业官网、英文网站、手机端网站、网站推广、申请域名、网页空间、企业邮箱。业务覆盖安乡地区。
import java.net.HttpURLConnection; import java.net.URI; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; 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.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.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:参数
public static String getHttpData(String host, String servUri, String reString) throws Exception { StringBuffer sb = new StringBuffer(); sb.append("getHttpData:host:" + host + ",servUri:" + servUri + ",reString:" + reString); String strResp = null; try { URI uri = new URIBuilder().setScheme("http").setHost(host).setPath(servUri) .setParameter("strInfo", reString).build(); HttpGet httpGet = new HttpGet(uri); CloseableHttpClient client3 = HttpClients.createDefault(); HttpResponse resp; resp = client3.execute(httpGet); if (resp.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { strResp = EntityUtils.toString(resp.getEntity()); logger.info("the return result:{}", strResp); } else { logger.info("Error Response:", resp.getStatusLine().toString()); throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF, CommonConstants.TASK_RELEASE_WCF_DESC); } } catch (Exception e) { logger.error(sb.toString() + ":" + e.getMessage(), e.getCause()); throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF, CommonConstants.TASK_RELEASE_WCF_DESC); } return strResp; }
HTTP 发送 post 请求
发送post分两种,我分两种的原因是为了让大家方便,想传对象和 json 可以直接复制过用就可以用,不用你们在转了。
第一种是直接接收json
参数明说:
url:url
json:参数
public static String doPostData(String url, String json) throws Exception { DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); String result = ""; HttpResponse res = null; try { StringEntity s = new StringEntity(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()); return HttpStatus.SC_OK + ""; } } catch (Exception e) { if(res == null) { return "HttpResponse 为 null!"; } throw new RuntimeException(e); } if(res == null || res.getStatusLine() == null) { return "无响应"; } return res.getStatusLine().getStatusCode() + ""; }
@Test public void test12() throws Exception { String HOST = "http://eipwcf.aspirecn.com/SvcEF/Service1.svc/WCF_EF_MSA_GetDataInfo_P"; HttpClient client = new HttpClient(); JSONObject json = new JSONObject(); json.put("msgId", msgId); String reslut=client.doPostData(HOST, json); }
第二种是参数是对象
参数说明:
url:url
tram:对象
public static String doHttpPostData(String url, TaskReleaseApprovalModel tram) throws Exception { StringBuffer sb = new StringBuffer(); sb.append("doHttpPostData:url:" + url + ",tram:" + tram.toString() + ",contentType:" + contentType); logger.info(sb.toString()); String tmpString = ""; HttpPost request = new HttpPost(url); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); ObjectMapper mapper = new ObjectMapper(); String jsonString; try { jsonString = mapper.writeValueAsString(tram); StringEntity entity = new StringEntity(jsonString, "UTF-8"); request.setEntity(entity); CloseableHttpClient client = HttpClients.createDefault(); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { tmpString = EntityUtils.toString(response.getEntity()); logger.info("the post result:tmpString:{}", tmpString); } else { logger.info("the post failure:tmpString:", tmpString); throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF, CommonConstants.TASK_RELEASE_WCF_DESC); } } catch (Exception e) { logger.error(sb.toString() + ":" + e.getMessage(), e.getCause()); throw new CommonBusinessException(CommonConstants.TASK_RELEASE_POSTWCF, CommonConstants.TASK_RELEASE_POSTWCF_DESC); } return tmpString; }
关于Java中怎么发送HTTP请求就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。