「已注销」 2015-12-12 09:34 采纳率: 25%
浏览 1367

为什么我用httpclient访问不到网络呢

public class MainActivity extends Activity {

public static final int SHOW_RESPONSE=1;
TextView text;

private Handler handler=new Handler();
public void handleMessage(Message msg){
    switch(msg.what){
    case SHOW_RESPONSE:
        String response=(String)msg.obj;
        text.setText(response);
    }
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button=(Button)findViewById(R.id.button);
    text=(TextView)findViewById(R.id.text);
    button.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
            sendRequestWithHttpClient();

        }
    });
}
private void sendRequestWithHttpClient(){
    Toast.makeText(MainActivity.this,"发出服务器请求", Toast.LENGTH_SHORT).show();
    new Thread(new Runnable(){
        public void run(){
            try{
                HttpClient httpClient=new DefaultHttpClient();

// HttpGet httpGet=new HttpGet("http://v5.pc.duomi.com/search-ajaxsearch-searchall?kw=jackson&pi=1&pz=5");
HttpGet httpGet=new HttpGet("http://www.baidu.com");
HttpResponse httpResponse=httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode()==200){
Toast.makeText(MainActivity.this,"请求响应成功", Toast.LENGTH_SHORT).show();
HttpEntity entity=httpResponse.getEntity();
String response=EntityUtils.toString(entity,"utf-8");

                    Message message=new Message();
                    message.what=SHOW_RESPONSE;
                    message.obj=response.toString();
                    handler.sendMessage(message);

// parseJSONWithJSONObject(response);
}
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}

  • 写回答

3条回答 默认 最新

  • Robot-C 2015-12-12 09:38
    关注

    HttpClient对比HttpUrlConnection有比较丰富的api,但是不利于扩展和升级,加上android团队在优化HttpClient方面并不积极。
    我比较倾向使用HttpUrlConnection,下面还是把两种访问网络的方法列出来以作比较。
    HttpClient:
    public String httpGet(String url, String params) throws......
    答案就在这里:访问网络之HttpClient和HttpUrlConnection
    ----------------------你好,人类,我是来自CSDN星球的问答机器人小C,以上是依据我对问题的理解给出的答案,如果解决了你的问题,望采纳。

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向