如何从Android API 16中的Url获取Html?

时间:2014-01-06 12:36:30

标签: android androidhttpclient

我是Android的新手,这个问题,我已多次尝试,但我无法做到。请帮助!

这是我的代码:

public class HttpHelper {
private static final int CONNECTION_TIMEOUT = 30000;
private static final int SOCKET_TIMEOUT = 10000;

public static String GET(String uri) {
    HttpParams params = new BasicHttpParams();

    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);

    HttpClient httpclient = new DefaultHttpClient(params);
    HttpResponse response;
    String data = "";

    try {
        response = httpclient.execute(new HttpGet(uri));
        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            data = out.toString();
        } else {
            // Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } 
    catch (ClientProtocolException e)
    {

    } catch (IOException e) 
    {

    }
    return data;
}

}

我这样称呼方法:

TextView jaxrs = (TextView) findViewById(R.id.jaxrs);
String result = HttpHelper.GET("http://www.baidu.com/");
jaxrs.setContentDescription(result);

当我运行此应用程序时,它会发出警报"不幸的是,*已停止。"

伙计们,logcat,我无法上传图片,所以请粘贴。

01-06 20:35:10.404: E/Trace(1102): error opening trace file: No such file or directory(2)    
01-06 20:35:10.904: D/AndroidRuntime(1102): Shutting down VM    
01-06 20:35:10.914: W/dalvikvm(1102): threadid=1: thread exiting with uncaught exception (group=0x40a13300)    
01-06 20:35:10.924: E/AndroidRuntime(1102): FATAL EXCEPTION: main    
01-06 20:35:10.924: E/AndroidRuntime(1102): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ibelieve.news/com.ibelieve.news.MainActivity}: android.os.NetworkOnMainThreadException
01-06 20:35:10.924: E/AndroidRuntime(1102):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)    
01-06 20:35:10.924: E/AndroidRuntime(1102):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)    
01-06 20:35:10.924: E/AndroidRuntime(1102):     at android.app.ActivityThread.access$600(ActivityThread.java:130)    
01-06 20:35:10.924: E/AndroidRuntime(1102):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)    
01-06 20:35:10.924: E/AndroidRuntime(1102):     at android.os.Handler.dispatchMessage(Handler.java:99)    
01-06 20:35:10.924: E/AndroidRuntime(1102):     at android.os.Looper.loop(Looper.java:137)    
01-06 20:35:10.924: E/AndroidRuntime(1102):     at android.app.ActivityThread.main(ActivityThread.java:4745)

1 个答案:

答案 0 :(得分:0)

您正在主要UI主题上的该活动中进行网络活动。这将引发exception。要解决此问题,请将网络操作(GET请求)移至其自己的ThreadAsyncTask