0

编辑:“你好”已被删除。所以,你好。

通过到达一个 URL,我应该得到一个字符串作为响应。所以我在这个网站上借了一部分代码,并用一种​​方法把我的字符串变成了一个变量。不幸的是,跳过了“Try”块,返回的字符串是“ * ”。我对这个脚本有什么误解?

变量“响应”是我应该得到的响应,还是其他?

提前致谢。

    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;
}
4

5 回答 5

0

这是我通常使用的(post而不是你的get,但应该是一样的)。

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);

    }
}
于 2013-01-15T22:26:51.217 回答
0

我想你是从 UI 线程调用它,而 Android 抛出一个异常,说你不能在主线程上进行网络 I/O。您可能没有看到这一点,因为您的 catch 块忽略了异常并且e.printStrackTrace()不会将异常转储到 logcat(您必须调用Log.e("tag", "boom", e);才能在日志中实际看到它。

首先确认您遇到了异常(修复日志记录,和/或重新抛出异常),如果是这样,那么您需要从另一个线程调用它,例如通过移动到 AsyncTask。

于 2013-01-16T03:09:05.813 回答
0

这是我们在应用程序中使用的,在获取 JSON 字符串时非常有用

    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();
    }
于 2013-01-16T02:26:56.907 回答
0

我不知道这是否正常工作,但这是你必须做的基本想法

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();

更新:

这是我的代码的简短片段,它可以正常工作:

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

顺便说一句,缓冲读数是您可以选择的最佳解决方案,但我真的不认为那是您的问题,因为我之前已经注意到 HTTPEntity不能为 null,所以我认为 HTTPRequest 有问题,也许尝试检查使用提琴手的请求结果。

于 2013-01-15T21:36:16.577 回答
0

我只是想在 Activity 而不是 AnsyncTask 中执行此操作。现在在 doInBackground 中效果更好。

谢谢你们。

于 2013-01-17T19:50:41.727 回答