Search code examples
javahttpurlconnectionbad-request

HttpUrlConnection BadRequest - Statuscode 400


I have implemented a class using HttpUrlConnection to get some data from the google geocoding api. When I'm using this code on android, it works properly. But as soon as I am using this code in another "normal" java program, I am getting the status-code 400 (BadRequest) sometimes. Here is my code:

HttpURLConnection c = null;
    StringBuilder sb = new StringBuilder();
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case HttpURLConnection.HTTP_OK:
            case HttpURLConnection.HTTP_CREATED:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();   
        }
    } catch (SocketTimeoutException ex){
        // Handle ...
    } catch (MalformedURLException ex) {
        // Handle ...
    } catch (IOException ex) {
        // Handle ...
    } finally {
        if (c != null) {
            try {
                c.disconnect();
            } catch (Exception ex) {

            }
        }
    }

I have a reliable internet connection and also the URL I am using to receive the data works, whenever I try it with my web browser. Thanks in advance!


Solution

  • Bad Request is often caused by inadequat URLs. As you mentioned not every URL gives this error, only a view of them. So it has to be something to do with that. Try the following code to ensure the correct encoding of the URL you are using:

    String url = ...;  // your url
    url = URLEncoder.encode(url,"UTF-8");
    // Use 'url' ...