我不知道为什么,但我在执行 GET 请求时收到了 POST 响应,这是我的方法:
public String performGetBrandCall(String requestURL) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + MainActivity.TOKEN);
conn.setDoInput(true);
conn.setDoOutput(true);
int responseCode=conn.getResponseCode();
Log.d(TAG, "Response Code: " + responseCode);
if (responseCode == HttpsURLConnection.HTTP_OK || responseCode == HttpsURLConnection.HTTP_CREATED) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
} else {
if (responseCode >= 400 && responseCode < 500){
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getErrorStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
} else {
response="";
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
我正在使用 setRequestProperty 添加 header ,这是我为请求设置的唯一“参数”,但我收到了帖子响应,但我不知道为什么。有什么建议吗?
最佳答案
根据 Android 开发者指南:
SetDoOutput 设置指示此 URLConnection 是否允许输出的标志。建立连接后无法设置。
仅当您使用 POST 请求时才必须调用此方法...如果您正在执行 GET 请求并且 SetDoOutput 为真,则您的请求将是 POST 请求。
我只删除了那一行,现在我得到了我的 GET 响应:
public String performGetCall(String requestURL) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer "+ MainActivity.TOKEN);
conn.setDoInput(true);
int responseCode=conn.getResponseCode();
Log.d(TAG, "Response Code: "+responseCode);
if (responseCode == HttpsURLConnection.HTTP_OK || responseCode == HttpsURLConnection.HTTP_CREATED) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
} else {
if (responseCode >= 400 && responseCode < 500){
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getErrorStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
} else {
response="";
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
关于android - 在 Get HttpURLConnection 请求中获取 POST 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33311607/