httpclient方式调用接口

本文提供了一个使用Java的HttpClient库进行POST请求提交表单数据的示例代码,展示了如何设置请求头、构建请求参数并发送到指定URL。
public class ToInterface {
/**
* post方式提交表单(模拟用户登录请求)
*/
public static void postForm() {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost("http://localhost:8000/send/sendWechatOrSMS");
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
String string = "{\"userId\":\"0\",\"productType\":\"0\",\"feeName\":\"0\",\"accountType\":\"0\",\"account\":\"0\",\"feeTime\":\"0\",\"send_type\":\"0\",\"ordNo\":\"No201512270001\",\"orderType\":\"儿童口腔就医卡\",\"orderDate\":\"淘宝网\",\"template_code\":\"sl_qy_payment\",\"phone\":\"18618265268\"}";
formparams.add(new BasicNameValuePair("string", string));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
postForm();
// interfaceUtil("http://192.168.10.89:8080/eoffice-restful/resources/sys/oadata", "usercode=10012");
// interfaceUtil("http://192.168.10.89:8080/eoffice-restful/resources/sys/oaholiday",
// "floor=first&year=2017&month=9&isLeader=N");
}
}

转载于:https://www.cnblogs.com/gaoxufei/p/10197254.html

<think>好的,用户现在想了解如何使用HttpClient调用接口,特别是示例代码。根据之前的对话历史,用户之前询问的是Maven依赖,现在转向具体的使用方法。需要参考用户提供的四个引用,其中引用了不同版本的HttpClient代码示例,比如引用1中的TestHttpClient类,引用3中的SSL忽略示例,还有引用4中的外部接口调用案例。 首先,用户可能对HttpClient的基本使用步骤不太清楚,需要分步骤讲解。需要注意到用户提供的引用中使用了不同版本的HttpClient,比如引用1使用的是旧版本的HttpClient(如PostMethod),而引用3使用的是DefaultHttpClient,这也是较旧的API。但当前HttpClient的最新版本是4.5.x,推荐使用CloseableHttpClient,所以可能需要更新示例代码到现代版本,避免用户混淆。 然后,需要检查用户提供的引用中的代码示例是否有错误或过时的地方。例如,引用1中的代码使用了PostMethod,这在HttpClient 4.x中已经被HttpPost替代,而且关闭连接的方式也不同。用户可能在实际操作中遇到问题,所以需要给出正确的代码结构。 另外,用户可能需要如何处理参数设置、头部信息、异常处理以及资源释放。引用3提到了忽略SSL证书,这也是一个常见需求,可能需要包含在示例中。同时,引用4提到参数通常以JSON格式传入,所以在POST请求示例中,可能需要演示如何发送JSON数据。 需要确保代码示例符合当前最佳实践,比如使用try-with-resources来自动关闭资源,避免资源泄露。此外,还要注意字符编码和内容类型的正确设置,如引用1中的UTF-8编码设置,引用3中的Content-Type头部。 可能用户是Java新手,需要详细的步骤说明,包括创建客户端、构建请求、执行请求、处理响应等。同时,要提醒依赖版本的重要性,避免出现版本冲突,如之前回答中提到的依赖冲突解决建议。 最后,生成相关问题时要围绕HttpClient的使用场景、高级配置、异常处理、性能优化等方面,帮助用户深入理解。</think>根据站内引用资料和当前HttpClient 4.5+版本的最佳实践,以下是三种常用接口调用方式的详细实现: ### 一、GET请求基础实现(含连接池优化) ```java // 创建全局连接池(引用[2]功能扩展) PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setMaxTotal(100); // 最大连接数 connManager.setDefaultMaxPerRoute(20); // 单路由最大连接数 try (CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connManager) .build()) { HttpGet httpGet = new HttpGet("https://api.example.com?param=value"); // 设置请求头(引用[3]头部配置) httpGet.setHeader("Accept", "application/json;charset=UTF-8"); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, StandardCharsets.UTF_8); System.out.println("响应状态:" + response.getStatusLine()); System.out.println("响应内容:" + result); } } catch (IOException e) { e.printStackTrace(); } ``` ### 二、POST请求进阶实现(支持JSON传参) ```java // 使用try-with-resources自动关闭资源(改进引用[1][3]的关闭方式) try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost("https://api.example.com/users"); // 构建JSON参数(符合引用[4]的传参规范) String jsonPayload = "{\"name\":\"张三\",\"age\":25}"; StringEntity entity = new StringEntity(jsonPayload, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 添加认证头(引用[3]的Bearer认证示例) httpPost.addHeader("Authorization", "Bearer your_token_here"); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println("创建成功:" + result); } else { System.err.println("请求失败:" + response.getStatusLine()); } } } catch (IOException e) { e.printStackTrace(); } ``` ### 三、HTTPS安全配置方案(解决引用[3]的SSL验证问题) ```java SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial((chain, authType) -> true) // 信任所有证书 .build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( sslContext, NoopHostnameVerifier.INSTANCE); try (CloseableHttpClient httpClient = HttpClients.custom() .setSSLSocketFactory(sslSocketFactory) .build()) { HttpGet httpsGet = new HttpGet("https://untrusted-cert-site.com"); try (CloseableHttpResponse response = httpClient.execute(httpsGet)) { System.out.println("HTTPS响应内容:" + EntityUtils.toString(response.getEntity())); } } ``` > **安全警告**:此方案仅用于测试环境,生产环境应使用正规CA证书 ### 四、最佳实践建议 1. **连接管理**:推荐使用连接池提升性能(如第一例所示) 2. **编码规范**:始终指定字符编码(如`StandardCharsets.UTF_8`) 3. **异常处理**:建议添加重试机制(可扩展`HttpRequestRetryHandler`) 4. **资源释放**:使用try-with-resources确保自动关闭[^1][^2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值