Android HttpURLConnection POST RequestMethod导致400错误代码
问题描述:
我必须通过长OpenStreetMaps立交api url请求。由于GET请求太长,我决定使用POST请求。不幸的是,改变RequestMethod解决了400错误代码(GET方法在200代码中查询结果相同)。Android HttpURLConnection POST RequestMethod导致400错误代码
这里是我的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;
}
答
删除应用程序/ json
从url中删除查询。然后将该查询字符串写入输出流。之后,您可以从输入流中读取
您应该以正常方式进行POST。相反,你使它成为application/json。那是错误的。此外,你没有发布任何数据。您没有将数据写入输出流。 – greenapps
'downloadUrl()'我想知道你想下载什么。 – greenapps
我删除了application/json行,但没有帮助。我试图下载Json OSM响应。通过GET方法,整个查询都在strUrl中,但是我的查询在很少的情况下变长了。网址查询如下所示:http://overpass-api.de/api/interpreter?data=[out:json] –
KamCho