这个HttpClient代码有什么问题?

时间:2014-02-13 06:01:56

标签: android http httpclient

我已经完成了下面的代码来获取xml结果,但它没有显示任何结果。我期待看到TextView txtVwHttp中的结果 - 我在mainActivities布局xml文件中有。有什么建议吗?我已经在manifest.xml中提供了互联网权限。

public class MainActivity extends Activity 
{
 TextView txtvw;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txtvw = (TextView)findViewById(R.id.txtVwHttp);

    //If connection doesnt work, even aftr givin permission for internet
     StrictMode.ThreadPolicy policy = new    StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);


    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("api.androidhive.info/pizza/?format=xml");
    HttpResponse response;

    try
    { response = httpClient.execute(httpGet);
          Log.i("Preda", response.getStatusLine().toString());
     HttpEntity entity = response.getEntity();
     if(entity != null)
       {     InputStream inStream = entity.getContent();
         String result = convertStreamToString(inStream);  // my defined method
             txtvw.setText(result);
             inStream.close();
         } } catch(Exception exc){}
    }

    private static String convertStreamToString(InputStream is)
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try
        { while((line = reader.readLine()) != null)
               {  sb.append(line + "\n"); }
        }

        catch(Exception exp)
            { exp.printStackTrace() ;}

        finally { try{ is.close(); }
             catch(IOException ioExp){ ioExp.printStackTrace(); }
    }

    return sb.toString();
    }      }

1 个答案:

答案 0 :(得分:0)

虽然学习如何使用DefaultHttpClient可能是一个很好的练习,但这不是一件非常实际的事情。您需要编写大量的样板代码,并且需要将调用包装在AsyncTask中以不阻止UI线程。如果你想要一个漂亮,干净和稳定的解决方案,我建议你使用众所周知的Android Asynchronous Http Client第三方库。来自网站:

“基于Apache的HttpClient库构建的基于异步回调的Android Http客户端。所有请求都是在应用程序的主UI线程之外发出的,但任何回调逻辑都将在使用回调创建的同一线程上执行Android的Handler消息传递。“

制作GET非常简单:

AsyncHttpClient client = new AsyncHttpClient();
client.get("api.androidhive.info/pizza/?format=xml", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
        txtvw.setText(response);
    }
});

PS将字符串作为字符串读取可以更简洁的方式完成。我总是这样做:

public static String getAsString(InputStream is) {
    if(is == null) {
        return null;
    }
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : null;
}

来自the following SO answer