【发布时间】:2018-12-04 12:57:42
【问题描述】:
我想用不同的方法调用 API:
使用 HttpClient 可以发帖和获取
我无法执行 PATCH 和 delete 方法,有没有人实现过这样的事情?以及如何?
发布方法一
public static String sendPost(String requestURL, Map<String, String> headers, String postParameters,
boolean withProxy) throws IOException {
HttpURLConnection con = createProxyHttpConnection(requestURL, withProxy);
con.setRequestMethod("POST");
con.setDoOutput(true);
for (Map.Entry<String, String> entry : headers.entrySet()) {
con.setRequestProperty(entry.getKey(), entry.getValue());
}
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParameters);
String response = IOUtils.toString(con.getInputStream(), "UTF-8");
wr.close();
con.disconnect();
return response;
}
发布方法二
public static HttpResponse sendPostBis(String requestURL, Map<String, String> headers, String payload,
boolean withProxy) throws IOException {
StringEntity sEntity = new StringEntity(payload,
ContentType.APPLICATION_FORM_URLENCODED);
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(requestURL);
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
request.setEntity(sEntity);
HttpResponse response = httpClient.execute(request);
return response;
}
我将方法 1 用于带有参数的 POST,而将方法 2 用于带有 json body 的 POST
错误消息 (如果我在 SoapUI 中将方法更改为 POST 而不是 PATCH,我将收到相同的消息)
{"error":"No route found for \u0022POST \RESOURCE","message":"No route found for \u0022POST RESOURCE"}
【问题讨论】:
-
你在使用任何框架吗?
-
发布您的 post 方法代码
-
我将编辑我的代码,不,我没有使用任何框架(它是一个 appium 应用程序,我绕过了一个无法在移动设备上自动化的步骤)@SamuelRobert
-
@SamuelRobert : 代码添加 :)
-
您必须在服务器端启用 PATCH 方法才能进行 PATCH 请求...