【问题标题】:Using Apache HTTP in Android Java在 Android Java 中使用 Apache HTTP
【发布时间】:2013-12-19 04:25:10
【问题描述】:

所以,首先,这是我的代码:

public class MainActivity extends Activity {


Button refresh;
TextView login;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    login = (TextView) findViewById(R.id.tvLogin);
    GetMethod test = new GetMethod();
    String returned;
    try{
        returned = test.getInternetData();
        login.setText(returned);
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

这是我的 Android 应用中的 MainActivity。这是GetMethod。

public class GetMethod {

public String getInternetData() throws Exception{
    BufferedReader in = null;
    String data = null;
    try{
        HttpClient client = new DefaultHttpClient();
        URI website = new URI("https://www.google.com/");
        HttpGet request = new HttpGet();
        request.setURI(website);
        HttpResponse response = client.execute(request);


        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String l = "";
        String nl = System.getProperty("line.separator");
        while((l = in.readLine()) != null){
            sb.append(l+nl);
        }
        in.close();
        data = sb.toString();
        return data;
    }finally {
        if(in != null){
            try{
                in.close();
                return data;
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}

}

我没有收到错误,也没有发现任何问题,但我很累,如果这很简单,我很抱歉。我一直在摆弄它。我发现 test.getInternetData() 上的代码出现异常。

编辑:澄清,它没有进入代码 login.setText(返回);

【问题讨论】:

    标签: java android apache http


    【解决方案1】:

    首先,您应该始终在单独的线程上执行长时间运行的查询(如网络请求)。 Android 有一个非常好的 AsyncTask,您可以为此目的进行扩展。我的猜测是 Android 杀死了你的请求是个例外。他们在 3.0 天后开始更严格地执行此操作,因此 UI 线程不会被阻塞(糟糕的用户体验)。

    您可以尝试另一件事。无需创建 URI,只需将 URI 字符串传递给 HttpGet 构造函数即可。然后获取字符串响应,使用EntityUtils.toString(response.getEntity());

    我应该注意,AsyncTasks 是一次性使用。因此,每次要执行查询时都必须创建一个新实例。所以不要使用匿名类,使用内部类。这是使用 AsyncTask 的示例:

    private class MyTask extends AsyncTask<String, Integer, String> {
       // This happens on the background thread, do not attempt to access anything on the UI thread
       @Override
       protected String doInBackground(String... urls) {
          if( urls == null || urls.length < 1 ) {
             return null;
          }
          HttpClient client = new DefaultHttpClient();
          HttpGet request = new HttpGet(urls[0]);
          HttpResponse response = client.execute(request);
    
          return EntityUtils.toString(response.getEntity());
       }
    
       // This happens on the UI thread. Do any visual updates here
       @Override
       protected void onPostExecute(String result) {
          if( result != null ) {
              // Do something with it
          }
       }
    }
    

    您可能注意到的一件事是您不能只在启动网络查询的函数中返回结果(因为它是异步发生的)。你会想要使用回调。如果您不知道那是什么,请查看Observer gang of 四模式。这是一种现在可以很好地为您服务的模式,并且在未来也会经常为您服务。

    【讨论】:

    • 谢谢,这让我走上了正轨,天哪,我在 3 小时后感到非常沮丧
    【解决方案2】:

    对于网络相关操作,您必须在 android 中使用 Asynctaskthreads 否则你会得到NetworkonMainThread Exception。

    参考here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多