0

Im trying to get the response from POST but when I do the Input throws and exception

     try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // Marcamos a 3s el tiempo maximo de espera
            conn.setReadTimeout(30000000);
            conn.setUseCaches(true);
            conn.setFixedLengthStreamingMode(bytes.length);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=UTF-8");
            // post the request
            // Abrimos una señal de salida
            OutputStream out = conn.getOutputStream();
            out.write(bytes);
            out.flush();
            String buffer;
            // Abrimos una señal de entrada
here is where android throws and exception
            InputStreamReader ip = new InputStreamReader(conn.getInputStream());
            BufferedReader in2 = new BufferedReader(ip);
            // Bucle que recoge todas las respuestas

            while ((buffer = in2.readLine()) != null) {
                Log.e(" ", buffer);
            }
            // Cerramos las señales de entrada y salida
            in2.close();
            out.close();

        } catch (IOException e) {
            Log.e(TAG, "ERROR" + e.toString());
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }

And LOG TAG shows this:

08-01 10:05:53.223: E/WooWMe GCM(798): ERRORjava.io.EOFException
08-01 10:05:53.223: W/System.err(798): java.io.EOFException
08-01 10:05:53.233: W/System.err(798):  at libcore.io.Streams.readAsciiLine(Streams.java:203)
08-01 10:05:53.233: W/System.err(798):  at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:560)
08-01 10:05:53.233: W/System.err(798):  at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:813)
08-01 10:05:53.233: W/System.err(798):  at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:274)
08-01 10:05:53.233: W/System.err(798):  at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
08-01 10:05:53.233: W/System.err(798):  at com.egartec.woowme.ChatActivity$3.doInBackground(ChatActivity.java:230)
08-01 10:05:53.233: W/System.err(798):  at com.egartec.woowme.ChatActivity$3.doInBackground(ChatActivity.java:1)
08-01 10:05:53.233: W/System.err(798):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-01 10:05:53.244: W/System.err(798):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-01 10:05:53.244: W/System.err(798):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-01 10:05:53.244: W/System.err(798):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-01 10:05:53.253: W/System.err(798):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-01 10:05:53.253: W/System.err(798):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-01 10:05:53.253: W/System.err(798):  at java.lang.Thread.run(Thread.java:856)
Shahrzad
  • 1,062
  • 8
  • 26

2 Answers2

10

If you use

conn.getInputStream()

everytime, it will throw a java.io.FileNotFoundException in the case when your request is unsuccessful, basically for any HTTP response code of 400 or above. In this case, your response body lies in

conn.getErrorStream()

Thus, you have to check the HTTP response code before you decide which stream to read from:

int status = conn.getResponseCode();
BufferedInputStream in;
if (status >= 400 ) {
    in = new BufferedInputStream( conn.getErrorStream() );
} else {
    in = new BufferedInputStream( conn.getInputStream() );
}

I did not include the reading from stream, since that's trivial :)

Stefan Anca
  • 1,386
  • 14
  • 23
0

I used http post once in my application, using this code, and it worked fine. You can try it if you wish.

public void posthttp()
{

    URL= your url
    InputStream is = null;
    String val1;
    String val2;
    ArrayList<NameValuePair> namevaluepair =new  ArrayList<NameValuePair>();

    //Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();

        namevaluepair.add(new BasicNameValuePair("val1",val1));
        namevaluepair.add(new BasicNameValuePair("val2",val2));


        String enc_url = urlEncode(URL);
        HttpPost httpPost = new HttpPost(enc_url );

         httpPost.setEntity(new UrlEncodedFormEntity(namevaluepair));
         HttpResponse httpResponse = httpClient.execute(httpPost);
         HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();            

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        is.close();
        String responseFromServer = sb.toString();

    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

}
Leigh
  • 28,765
  • 10
  • 55
  • 103
WISHY
  • 11,067
  • 25
  • 105
  • 197