HttpClient

来源:互联网 发布:mac误删文件怎么恢复 编辑:程序博客网 时间:2024/05/21 07:51

public class MainActivity extends Activity {

@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);}public void requestweather(View v){    new Thread(){        public void run() {            //1.创建出一个HttpClient            HttpClient hc=new DefaultHttpClient();            //2.创建HttpGet对象            try {                //对参数进行编码                 String citydata=URLEncoder.encode("北京", "utf-8");                HttpGet hg=new HttpGet("http://v.juhe.cn/weather/index?cityname="+citydata+"&dtype=&format=&key=d518c53e9f8bd40ba1784ca8448223b8");                //3.执行请求                HttpResponse response = hc.execute(hg);                //4.得到结果码,并判断                 int code=response.getStatusLine().getStatusCode();                if(code==200){                    //5.得到结果数据                    HttpEntity result = response.getEntity();                    //将HttpEntity转换成String字符串                    String content=EntityUtils.toString(result);                    Log.d("zzz", content);                }            } catch (UnsupportedEncodingException e) {                // TODO Auto-generated catch block                e.printStackTrace();            } catch (ClientProtocolException e) {                // TODO Auto-generated catch block                e.printStackTrace();            } catch (IOException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        };    }.start();}

}

<Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="请求天气数据"        android:onClick="requestweather" />
原创粉丝点击