0

我正在尝试开发一个从 Web 服务获取数据并显示它的简单应用程序

当他打电话时它会抛出异常response.execute(client)

package com.example.webbasedapp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class GETMethods {

public String getInternetData() throws Exception{
    BufferedReader in=null;
    String Data=null;
    try{

        HttpClient client=new DefaultHttpClient();
        URI web=new URI("http://www.mybringback.com/");
        HttpGet request = new HttpGet();
        request.setURI(web);
        HttpResponse reponse=client.execute(request);
        Log.v("response code", reponse.getStatusLine()
                .getStatusCode() + ""); 
        InputStream inp=reponse.getEntity().getContent();
        in=new BufferedReader(new InputStreamReader(inp));
        StringBuffer buf=new StringBuffer();
        String l="";
        String nl=System.getProperty("line.separator");
        while((l=in.readLine())!=null){
            buf.append(l+nl);
        }
        in.close();
        Data=buf.toString();
        return Data;

    }finally{
        if(in!=null){
            try{
                in.close();
                return Data;
            }catch (Exception e){
                Log.d("error",e.toString());
            }
        }
    }
}
}

这是我的主要活动

package com.example.webbasedapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class Home extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    TextView test = (TextView) findViewById(R.id.data);
    GETMethods data = new GETMethods();
    String d = null;
    try {
        d = data.getInternetData();
        // test.setText(d);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        d = "bla";
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        // Log.d("testW",e.getMessage());
    }
    test.setText(d);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.home, menu);
    return true;
}

}
4

1 回答 1

4

由于潜在的挂断问题,您正在尝试访问不允许的 UI 线程上的网络。查看AysncTask并将 GETMethods 实现为其中之一。它看起来像这样:

public class GETMethods extends AsyncTask<String, Void, String>{
    protected void doInBackground(String... params){
        YourNetworkCode
    }
}
于 2013-07-15T19:20:19.277 回答