网络编程
2015-11-28 22:41
621 查看
HttpURLConnection
连接网络的操作要放入一个子线程,使用handler更新ui
声明网络权限
效果:
HttpClient
声明网络权限
效果:
可以看出比httpURLConnection内容多了很多
Main
权限
效果
连接网络的操作要放入一个子线程,使用handler更新ui
package com.example.testsometing; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.TextView; public class MainActivity extends Activity { Handler handler ; TextView tv_response; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_response = (TextView) this.findViewById(R.id.response); handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: tv_response.setText(msg.obj.toString()); break; default: break; } } }; new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL("http://www.baidu.com"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET");//代表我想要获取,POST代表我想要传递参数给网站 connection.setConnectTimeout(3000); connection.setReadTimeout(8000); //connection.setRequestMethod("POST"); //DataOutputStream out = new DataOutputStream(Connection.getOutputStream()); //out.writeBytes("username=admin&password=123456"); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while((line=reader.readLine()) != null){ response.append(line); } Message msg = new Message(); msg.what = 1; msg.obj = response; handler.sendMessage(msg); } catch (IOException e) { e.printStackTrace(); } } }).start(); } }
声明网络权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
效果:
HttpClient
package com.example.testsometing; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.TextView; public class MainActivity extends Activity { Handler handler ; TextView tv_response; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_response = (TextView) this.findViewById(R.id.response); handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: tv_response.setText(msg.obj.toString()); break; default: break; } } }; new Thread(new Runnable() { @Override public void run() { try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://www.baidu.com"); HttpResponse httpResponse = httpClient.execute(httpGet); /* HttpGet httpPost = new HttpPost("http://www.baidu.com"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username","admin")); params.add(new BasicNameValuePair("password","123456")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"utf-8"); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost); */ String response; if(httpResponse.getStatusLine().getStatusCode() == 200){ //请求和相应都成功 HttpEntity entity = httpResponse.getEntity(); response = EntityUtils.toString(entity,"utf-8"); } else{ response = "error"; } Message msg = new Message(); msg.what = 1; msg.obj = response; handler.sendMessage(msg); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ).start(); } }
声明网络权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
效果:
可以看出比httpURLConnection内容多了很多
HttpUrlConnection更新 2016/02/24
使用HttpUrlConnection下载图片到SD卡并显示Main
String url = "http://imgsrc.baidu.com/forum/pic/item/3582724c510fd9f9e10ab386252dd42a2934a4bf.jpg"; new MyThread(url, iv, handler).start();
public class MyThread extends Thread { private ImageView iv; private Handler handler; String url; public MyThread(String url, ImageView iv, Handler handler) { this.url = url; this.iv = iv; this.handler = handler; } @Override public void run() { try { URL httpUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection(); conn.setReadTimeout(5000); conn.setRequestMethod("GET"); conn.setDoInput(true); InputStream in = conn.getInputStream(); FileOutputStream out = null; String fileName = String.valueOf(System.currentTimeMillis()); File downloadFile = null; //判断SD卡是否挂载 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File parent = Environment.getExternalStorageDirectory(); downloadFile = new File(parent, fileName); out = new FileOutputStream(downloadFile); } byte[] b =new byte[2*1024]; int len; if (out!=null) { while ((len=in.read(b))!=-1) { out.write(b,0,len); } } if (downloadFile != null) { final Bitmap bmp = BitmapFactory.decodeFile(downloadFile.getAbsolutePath()); handler.post(new Runnable() { @Override public void run() { iv.setImageBitmap(bmp); } }); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
权限
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
效果
相关文章推荐
- 一行代码解决各种IE兼容问题,IE6,IE7,IE8,IE9,IE10 http://www.jb51.net/css/383986.html
- iOS网络监控— BMReachability
- Rosenblatt感知器详解
- redhat 的网络配置
- iOS开发网络-网络编程基础
- 最全的CSS浏览器兼容问题http://www.68design.net/Web-Guide/HTMLCSS/37154-1.html
- Debian GNU/Linux安装HP网络打印机
- VMware下CentOS网络搭建
- 高清网络视频监控系统中交换机的选择
- Http协议下的浏览器与服务器的交互
- Tinyhttpd源码解析
- administrator内置账户“ 网络无法访问,你可能没有权限使用网络资源,请与管理员联系...” 解决办法
- 【读书笔记】:网络安全复习
- 大端和小端(网络字节序和主机字节序)
- Java 网络编程
- android gradle project的时候connect refused:connect或者卡在building gradle download https:
- 零碎问题收集(自己收集的问题,解决方法有自己的、也有转自网络)
- https://locahost:1158/em
- 【转】Html表头Meta http-equiv属性详解
- 网络基础-再议TCP