HttpResponse.execute()抛出异常

时间:2013-07-15 19:16:39

标签: android web-services http

我正在尝试开发一个简单的应用程序从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;
}

}

1 个答案:

答案 0 :(得分:4)

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

public class GETMethods extends AsyncTask<String, Void, String>{
    protected void doInBackground(String... params){
        YourNetworkCode
    }
}