1

I'm trying to fetch data from an API via HttpURLConnection but getting IOException with a message:

Invalid Http response

However, when I paste the request url to the browser I'm getting the correct response with 200 as a response code. Here's the code what's failing:

public static String sendRequest(String url) throws IOException {
    HttpURLConnection urlConnection = null; 
    String out = null;
    System.setProperty("http.keepAlive", "false");
    try {
        URL serverAddress = new URL(url);
        urlConnection = (HttpURLConnection) serverAddress.openConnection();
        urlConnection.setReadTimeout(TIME_OUT_LENGTH);
        urlConnection.setRequestMethod(REQUEST_METHOD_GET);
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        out = Connection.readStream(in);
    } catch (IOException e) {
        System.out.println(e.getCause());
        InputStream is = new BufferedInputStream(urlConnection.getErrorStream());
        out = Connection.readStream(is);
    } finally {
        urlConnection.disconnect();
        System.out.println(out);
        return out;
    }
}

private static String readStream(InputStream in) throws IOException {
    String line;
    BufferedReader r = new BufferedReader(new InputStreamReader(in));
    StringBuilder sb = new StringBuilder();
    while((line = r.readLine()) != null) 
        sb.append(line);
    return sb.toString();
}

Anyone seeing what I'm doing wrong?

--- EDIT ----

Stack trace:

at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1341)
at java.net.URL.openStream(URL.java:1037)
at com.urhola.cheddar.connection.Connection.sendRequest(Connection.java:33)
at com.urhola.cheddar.request.Request.execute(Request.java:63)
at com.urhola.cheddar.request.LineInformationRequest.execute(LineInformationRequest.java:36)
at tester.Client.main(Client.java:54)
J.Koskela
  • 421
  • 1
  • 6
  • 19

1 Answers1

0

Okay, I switched to Apaches HTTP client and it threw an exception saying url parameters were invalid. So I checked and noticed I was sending a parameters (which often included spaces) without encoding them. After encoding parameters (example below) everything worked beautifully.

URLEncoder.encode(parameter, "UTF-8");
J.Koskela
  • 421
  • 1
  • 6
  • 19