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; 
} 
+0

您应该以正常方式进行POST。相反,你使它成为application/json。那是错误的。此外,你没有发布任何数据。您没有将数据写入输出流。 – greenapps

+0

'downloadUrl()'我想知道你想下载什么。 – greenapps

+0

我删除了application/json行,但没有帮助。我试图下载Json OSM响应。通过GET方法,整个查询都在strUrl中,但是我的查询在很少的情况下变长了。网址查询如下所示:http://overpass-api.de/api/interpreter?data=[out:json] KamCho

删除应用程序/ json

从url中删除查询。然后将该查询字符串写入输出流。之后,您可以从输入流中读取

HTTP错误400错误的请求错误。这意味着你发送错误的请求。当您通过POST获取带有GET和HTTP 400的HTTP 200时,您调用的HTTP方法是GET而不是POST。所以你不能发送POST请求到GET方法。

+0

谢谢你的回答。据此:http://overpass-api.de/command_line.html OSM立交api支持GET和POST方法。尽管如此,如果我的代码是好的,那么它可能不是真的... – KamCho

+0

糟糕的请求只是由json方法引起的。不是因为它是一个POST。 POST是可能的,但应该以正确的方式完成。 – greenapps