【发布时间】:2017-09-11 10:29:58
【问题描述】:
我必须通过长 OpenStreetMaps overpass 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;
}
【问题讨论】:
-
您应该以正常方式发布。相反,您将其设为 application/json。那是错误的。此外,您没有发布任何数据。您没有将数据写入输出流。
-
downloadUrl()我想知道你想下载什么。 -
我删除了 application/json 行,但没有帮助。我正在尝试下载 Json OSM 响应。通过 GET 方法,整个查询都在 strUrl 中,但在少数情况下我的查询变得很长。 URL 查询如下所示:overpass-api.de/api/interpreter?data=[out:json]<long OSM 在此处查询>
-
您没有发布任何数据!那么这怎么可能奏效呢?您没有发布那么长的 osm 查询字符串。
-
从 url 中删除查询。然后将该查询字符串写入输出流。之后,您可以从输入流中读取。
标签: android post httpurlconnection openstreetmap urlconnection