Android HttpURLConnection POST RequestMethod 导致 400 错误代码
Android HttpURLConnection POST RequestMethod results in 400 error code
我必须通过长 OpenStreetMaps 立交桥 api url 请求。由于 GET 请求太长,我决定使用 POST 请求。不幸的是,更改 RequestMethod 解析为 400 错误代码(使用 GET 方法相同的查询结果为 200 代码)。
这是我的 HttpURLConnection 代码:
public String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
Log.wtf("JSON","connection started...");
// Connecting to url
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
Log.wtf("KOD",Integer.toString(urlConnection.getResponseCode()));
// Reading data from url
iStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuilder sb = new StringBuilder();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.wtf("ExceptionWhileUrlDownload", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
HTTP 错误 400 是错误的请求错误。这意味着您发送了错误的请求。当您使用 GET 获得 HTTP 200 并使用 POST 获得 HTTP 400 时,您调用的 HTTP 方法是 GET 而不是 POST。所以你不能向 GET 方法发送 POST 请求。
删除 application/json
从 url 中删除查询。然后将该查询字符串写入输出流。之后你可以从输入流中读取
我必须通过长 OpenStreetMaps 立交桥 api url 请求。由于 GET 请求太长,我决定使用 POST 请求。不幸的是,更改 RequestMethod 解析为 400 错误代码(使用 GET 方法相同的查询结果为 200 代码)。
这是我的 HttpURLConnection 代码:
public String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
Log.wtf("JSON","connection started...");
// Connecting to url
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
Log.wtf("KOD",Integer.toString(urlConnection.getResponseCode()));
// Reading data from url
iStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuilder sb = new StringBuilder();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.wtf("ExceptionWhileUrlDownload", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
HTTP 错误 400 是错误的请求错误。这意味着您发送了错误的请求。当您使用 GET 获得 HTTP 200 并使用 POST 获得 HTTP 400 时,您调用的 HTTP 方法是 GET 而不是 POST。所以你不能向 GET 方法发送 POST 请求。
删除 application/json
从 url 中删除查询。然后将该查询字符串写入输出流。之后你可以从输入流中读取