我写了一个简单的方法来使用apache HTTPClient获取一些字符串数据,但是当我在手机上运行它时会返回一个空白屏幕;我正在尝试在textarea中显示数据。清单具有互联网许可。任何人都可以指出我可能做错了什么吗?
public String getInternetData() throws Exception
{
BufferedReader in = null;
String data = null;
try
{
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.yahoo.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();
}
}
}
}
为了完整性,我添加了用于查看数据的代码。
public class MainActivity extends Activity {
TextView httpStuff;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpStuff = (TextView) findViewById(R.id.tvHttp);
GetMethodEx test = new GetMethodEx();
String returned;
try {
returned = test.getInternetData();
httpStuff.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
你可能正在获取UI线程错误的网络,并且因为它在try catch中,应用程序没有崩溃
你应该只在后台线程中调用网络操作,或者是非常适合的那个
的AsyncTasks您的HTTP客户端和请求数据没有任何问题,问题确实在于您的onCreate方法
尝试以这种方式重写
public class MainActivity extends Activity {
TextView httpStuff;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpStuff = (TextView) findViewById(R.id.tvHttp);
AsyncTask<Void,Void,String>getDataTask = new AsyncTask<Void,Void,String>(){
@Override
protected String doInBackground(Void... params){
GetMethodEx test = new GetMethodEx();
String returned = test.getInternalData();
return returned;
}
@Override
protected void onPostExecute(String returned){
httpStuff.setText(returned);
}
}
}
getDataTask.execute();
}