java中HttpsPost和CloseableHttpClient如何使用
这篇文章给大家介绍java中HttpsPost和CloseableHttpClient如何使用,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
成都做网站、网站建设介绍好的网站是理念、设计和技术的结合。创新互联拥有的网站设计理念、多方位的设计风格、经验丰富的设计团队。提供PC端+手机端网站建设,用营销思维进行网站设计、采用先进技术开源代码、注重用户体验与SEO基础,将技术与创意整合到网站之中,以契合客户的方式做到创意性的视觉化效果。
//请求json public static String HttpsPost(String url, Mapparam) throws Exception{ String respContent =""; String restServiceURL = url; System.out.println(restServiceURL); CloseableHttpClient client = HttpClients.createDefault(); //设置传入参数 StringEntity entity = new StringEntity(JSONObject.toJSONString(param), "utf-8"); HttpPost httpGet = new HttpPost(restServiceURL); httpGet.addHeader("Content-Type","application/json;charset=UTF-8"); httpGet.setEntity(entity); HttpResponse resp = client.execute(httpGet); int statusCode = resp.getStatusLine().getStatusCode(); if ( 200==statusCode ) { HttpEntity he = resp.getEntity(); respContent = EntityUtils.toString(he, "utf-8"); }else { log.error("请求第三方异常,状态码{},地址{}",statusCode,url); } return respContent; }
/** * http请求 application/x-www-form-urlencoded */ public static String HttpsPostXw(String url, Mapparam) throws Exception{ String respContent =""; String restServiceURL = url; CloseableHttpClient client = HttpClients.createDefault(); //设置传入参数 HttpPost httpGet = new HttpPost(restServiceURL); httpGet.setHeader("Content-type", "application/x-www-form-urlencoded"); List nvps = new ArrayList (); if(param!=null){ for (Map.Entry entry : param.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } //设置参数到请求对象中 httpGet.setEntity(new UrlEncodedFormEntity(nvps, "utf-8")); //装填参数 if(param!=null){ for (Map.Entry entry : param.entrySet()) { httpGet.setHeader(entry.getKey(),entry.getValue()); } } HttpResponse resp = client.execute(httpGet); int statusCode = resp.getStatusLine().getStatusCode(); if ( 200==statusCode ) { HttpEntity he = resp.getEntity(); respContent = EntityUtils.toString(he, "utf-8"); }else { log.error("请求第三方异常,状态码{},地址{}",statusCode,url); } return respContent; }
关于java中HttpsPost和CloseableHttpClient如何使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
分享标题:java中HttpsPost和CloseableHttpClient如何使用
分享路径:http://azwzsj.com/article/pphpco.html