【发布时间】:2019-07-21 21:26:14
【问题描述】:
请不要将我的问题与使用 HttpURLConnection 发送带有 POST 请求的正文混淆。
我想使用 HttpURLConnection 发送带有 GET 请求的正文。这是我正在使用的代码。
public static String makeGETRequest(String endpoint, String encodedBody) {
String responseJSON = null;
URL url;
HttpURLConnection connection;
try {
url = new URL(endpoint);
connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
OutputStream outputStream = connection.getOutputStream();
outputStream.write(encodedBody.getBytes());
outputStream.flush();
Util.log(connection,connection.getResponseCode()+":"+connection.getRequestMethod());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseChunk = null;
responseJSON = "";
while ((responseChunk = bufferedReader.readLine()) != null) {
responseJSON += responseChunk;
}
bufferedReader.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
Util.log(e, e.getMessage());
}
return responseJSON;
}
会根据 connection.getInputStream() 和 connection.getOutPutStream() 自动识别请求类型。
当您调用 connection.getOutPutStream() 时,请求类型会自动设置为 POST,即使您已将请求类型明确设置为 GET使用 connection.setRequestMethod("GET")。
问题是我正在使用 3rd 方 Web 服务 (API),它接受请求参数作为带有 GET 请求的正文
<get-request>
/myAPIEndPoint
body = parameter1=value as application/x-www-form-urlencoded
<response>
{json}
我很清楚大多数情况下 GET 没有请求正文,但许多 Web 服务经常使用带有参数的 GET 请求作为正文而不是查询字符串。请指导我如何在不使用任何第三方库(OkHttp、Retrofit、Glide 等)的情况下在 android 中发送带有 body 的 GET 请求
【问题讨论】:
-
HttpURLConnectiondoes not support this,可能是因为that sort of structure was somewhat out of spec back when Java was first created。我不确定是否有任何图书馆支持这一点。您需要打开自己的套接字连接并手动与服务器通信。这可能不愉快。 -
对于那些阅读这个问题愿意使用库的人来说,似乎OkHttp does not support this either,虽然你也许可以使用Apache HttpClient库的独立打包(见this)。
-
请使用库
-
不支持带body的HTTP GET,因为它是幂等的,这意味着多次调用这个方法应该没有任何副作用。所以请不要违背标准。使用支持请求正文的方法。
标签: java android api web-services get