HttpUrlConnection Get请求网络数据
2016-10-27 12:19
351 查看
注:
1.请求数据是耗时操作,需要创建一个子线程进行网络请求
2.因为是联网操作,需要添加权限:
3.需要用到的网站:www.juhe.cn
4.按步骤进行。
public class MainActivity extends Activity {
}
1.请求数据是耗时操作,需要创建一个子线程进行网络请求
2.因为是联网操作,需要添加权限:
3.需要用到的网站:www.juhe.cn
4.按步骤进行。
public class MainActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnSearch=(Button)findViewById(R.id.button1); btnSearch.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { new MyThread().start(); } }); } class MyThread extends Thread{ @Override public void run() { //进行http协议编程,访问网络数据 requestDataByGet(); } } private void requestDataByGet() { String path="http://v.juhe.cn/postcode/query?postcode=075600&key=6e5e1292af5ebfd8eff8f2392187f5bd"; try { //1.创建URL对象 URL url=new URL(path); //2.打开连接,获得HttpURLConnction对象 HttpURLConnection conn=(HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET");//设置请求方法-默认是get请求 conn.setConnectTimeout(5000);//设置连接超时时间 //3.获取响应码 int code=conn.getResponseCode(); if(code==200){ //4.得到输入流 InputStream stream=conn.getInputStream(); //将字节流转换成字符流 BufferedReader reader=new BufferedReader(new InputStreamReader(stream)); String content=null; StringBuilder sb=new StringBuilder(); while((content=reader.readLine())!=null){ sb.append(content); } Log.d("zzz", sb.toString()); }else{ Toast.makeText(this, "请求失败!"+code, 1).show(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
}
相关文章推荐
- 第十二篇:Android GET请求获取网络数据以及POST数据(使用HttpURLConnection)
- 使用HttpURLConnection和使用HttpClient方式请求网络采用get方式和post方式请求数据
- Android25图灵聊天项目------HttpURLConnection请求get文本数据
- httpURLConnection-网络请求的两种方式-get请求和post请求
- HttpURLConnection_Handler网络请求数据5
- android 请求网络数据 HttpURLConnection
- HttpURLConnection请求数据(GET)并用JSON解析数据(二)
- 使用HttpURLConnection采用get方式或post方式请求数据
- HttpURLConnection,get,post,网络请求
- http请求远程接口获得JSON数据(1) --- 利用HttpURLConnection发送post/get请求
- Android使用HttpURLConnection请求网络返回JSON数据并解析
- httpURLConnection-网络请求的两种方式-get请求和post请求
- Android中使用HttpURLConnection和HttpClient实现GET和POST请求访问网络
- HttpURLConnection 网络请求数据
- 使用HttpURLConnection请求Gson网络解析数据
- HttpUrlConnection两种请求数据的方式get和post提交数据
- Android用httpURLConnection发送post网络请求并拿到数据
- 【黑马Android】(05)短信/查询和添加/内容观察者使用/子线程网络图片查看器和Handler消息处理器/html查看器/使用HttpURLConnection采用Post方式请求数据/开源项目
- android(21)(使用HttpURLConnection,HttpClient和AsyncHttpClient分别实现post和get请求数据)
- HttpURLConnection_get 网络请求