HTTP request should return a string

2019-08-30 10:22发布

问题:

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 string into a variable. Unfortunatelly, the "Try" block is skipped and the returned string is "*". What do I have misunderstood something about this script ?

Is the variable "response" what I should get as a response, or something else ?

Thanks in advance.

    private String getMessages() {
    String response = "***";
    try {
        HttpClient client = new DefaultHttpClient();  
        String getURL = "http://***.com/message/";
        HttpGet get = new HttpGet(getURL);
        HttpResponse responseGet = client.execute(get);  
        HttpEntity resEntityGet = responseGet.getEntity();  
        if (resEntityGet != null) {  
            // do something with the response
            response = EntityUtils.toString(resEntityGet);
            Log.i("GET RESPONSE", response);
        }
    } catch (Exception e) {
        e.printStackTrace();

    }

    return response;
}

回答1:

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

StringBuilder builder = new StringBuilder();
InputStream content = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
String response = 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 = new byte[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.



回答2:

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

public String getMessage(){
InputStream is = null;      
String result = "";
    //http post
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(<url>);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
            nameValuePairs.add(new BasicNameValuePair("var1", var1));   

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
    }
    //convert response to string
    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 + "\n");
            }
            is.close();
            result=sb.toString();
    }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }
    Log.i("result string", result);

    }
}


回答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();
    }


回答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.



回答5:

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

Thank you all.