Skip to content Skip to sidebar Skip to footer

Http Request Should Return A String

Edit: 'hello' has been deleted. So, hello. By reaching an URL, I should get a string as response. So I borrowed a part of code on this website and adapted in a method to get my str

Solution 1:

I don't know if this works correctly but this is the basic idea what you must do

StringBuilderbuilder=newStringBuilder();
InputStreamcontent= entity.getContent();
                    BufferedReaderreader=newBufferedReader(newInputStreamReader(content));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
Stringresponse= builder.toString();

UPDATE:

This is a short snipped of my code, which is working without problems:

int statusCode = mResponse.getStatusLine().getStatusCode();
                    InputStream is = null;
                    StringBuilder stringBuilder = new StringBuilder();
                    if (statusCode == HttpStatus.SC_OK) {
                        HttpEntity entity = mResponse.getEntity();
                        if (entity != null) {
                            try {
                                is = entity.getContent();
                            } catch (IllegalStateException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            byte[] buffer = newbyte[1024];
                            int length;
                            try {
                                while ((length = is.read(buffer)) > 0) {
                                    stringBuilder.append(new String(buffer, 0, length));
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

by the way the buffered reading is the best solution you can choose, but I dont really think thats your problem, as I have noticed before the HTTPEntity must not be null, so I assume there is something wrong with the HTTPRequest, maybe try to check the request-results using fiddler.

Solution 2:

Here is what I usually use (post instead of your get but should be the same).

public String getMessage(){
InputStreamis=null;      
Stringresult="";
    //http posttry{
            HttpClienthttpclient=newDefaultHttpClient();
            HttpPosthttppost=newHttpPost(<url>);
            List<NameValuePair> nameValuePairs = newArrayList<NameValuePair>();  
            nameValuePairs.add(newBasicNameValuePair("var1", var1));   

            httppost.setEntity(newUrlEncodedFormEntity(nameValuePairs));

            HttpResponseresponse= httpclient.execute(httppost);
            HttpEntityentity= response.getEntity();
            is = entity.getContent();

    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
    }
    //convert response to stringtry{
            BufferedReaderreader=newBufferedReader(newInputStreamReader(is,"iso-8859-1"),8);
            StringBuildersb=newStringBuilder();
            Stringline=null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
    }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }
    Log.i("result string", result);

    }
}

Solution 3:

This is what we are using in our apps, very useful in getting JSON strings

    String response = "";
    try {
        HttpClient httpClientpost = new DefaultHttpClient();
        String postURL = "http://somepostaddress.com";
        HttpPost post = new HttpPost(postURL);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("postName1", "value1"));
        params.add(new BasicNameValuePair("postName2", "value2"));
        params.add(new BasicNameValuePair("postName3", "value3"));
        //And So On

        UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params);
        post.setEntity(ent);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        HttpResponse responsePOST = httpClientpost.execute(post);
        HttpEntity resEntity = responsePOST.getEntity();

        //Server Response
        response = EntityUtils.toString(resEntity);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Solution 4:

I'd image that you're calling this from the UI thread, and Android is throwing an exception saying you can't do network I/O on the main thread. You're probably not seeing this as your catch block ignores the exception and e.printStrackTrace() will not dump the exception to logcat (you have to call Log.e("tag", "boom", e); to actually see it in the log.

Start by confirming that you're hitting the exception (fix the logging, and/or rethrow the exception), and if it is that, then you'll need to call this from another thread, e.g. by moving into an AsyncTask.

Solution 5:

I was just trying to do it in an Activity instead of an AnsyncTask. Works better now in the doInBackground.

Thank you all.

Post a Comment for "Http Request Should Return A String"