Android HttpClient问题

时间:2011-03-24 19:15:03

标签: android-2.2-froyo

根据Eclipse IDE,代码中没有错误。但是当我试图在设备中运行它时,它会给出一条错误消息。

package com.android.mypackage;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import org.apache.http.entity.BufferedHttpEntity;
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 org.apache.http.HttpEntity;
import android.widget.TextView;

public class MyActivity extends Activity 
{
    TextView textview;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick(View v)
            {
                try 
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpGet httpget = new HttpGet("http://www.google.com");
                    HttpResponse httpresponse = httpclient.execute(httpget);
                    HttpEntity httpentity = httpresponse.getEntity();
                    if (httpentity != null)
                    {
                        httpentity = new BufferedHttpEntity(httpentity);
                    }
                }
                catch (Exception e)
                {
                    System.out.println("Exception e");
                    textview.setText(e.getMessage());
                }
            };
        });
    }        
}

1 个答案:

答案 0 :(得分:0)

试试这个:添加这一行

httpget.addHeader("User-Agent", "Android");

在执行httpget之前。