通过使用
HttpClient
,我正在尝试 API 自动化。当我进行 GET 调用时,一切都很好。但是当我进行 POST 调用时 - 获取代码:404 作为 Http 响应。
示例:
Request URL : Base_url + service_url + params
Post body : {"key1":"value1","key2":"value2"}
使用 REST 客户端 - 我得到了正确的响应。 使用 Java 代码 - 我收到 404 错误代码。
如何使用
HttpClient
拨打电话?
404
是“FileNotFound” - 您应该显示异常...
按照要求 - 这是 HttpClient 的简短示例:
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://base-url/service-url?params");
StringEntity body=new StringEntity("{\"key1\":\"value1\",\"key2\":\"value2\"}");
request.setEntity(body);
HttpResponse response = httpClient.execute(request);
// Do something with response
}catch (Exception ex) {
//Something bad happended - deal with it.
ex.printStackTrace()
}