HttpClient远程RPC调用
1、pom.xml依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
2、post调用,JSON参数
/** * HttpClient Json 请求接口 * @return json */ public static JSONObject request(String url,JSONObject json) { RequestConfig config = RequestConfig.custom() .setConnectTimeout(8 * 1000) //设置连接超时时间,单位毫秒 .setSocketTimeout(8 * 1000) //请求获取数据的超时时间,单位毫秒 .build(); CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); HttpPost post = new HttpPost(url); StringEntity params = new StringEntity(json.toString(), "utf-8"); params.setContentType("text/html;charset=UTF-8"); params.setContentEncoding("UTF-8"); post.setEntity(params); JSONObject response = null; try { HttpResponse res = httpclient.execute(post); if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ String result = EntityUtils.toString(res.getEntity());// 返回json格式: response = JSONObject.parseObject(result); }else{ System.out.println(res.getStatusLine().getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } return response; }
以上内容原创来自每特学院,每特学员学习并整理!
给学院打波广告:
http://www.mayikt.com/
浙公网安备 33010602011771号