URLConnection是个抽象类,它有两个直接子类分别是HttpURLConnection和JarURLConnection。另外一个重要的类是URL,通常URL可以通过传给构造器一个String类型的参数来生成一个指向特定地址的URL实例。
JDK自带的请求方式,包名: java.net.HttpURLConnection;
HttpURLConnection请求的类别:
分为二类,GET与POST请求。二者的区别在于:
1: get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
2: post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
效果图:
代码:
1 public class Util {
2
3 /***
4 * get请求方式
5 * @param urlPath
6 * @return
7 */
8 public static String get(String urlPath) {
9 HttpURLConnection conn = null; // 连接对象
10 InputStream is = null;
11 String resultData = "";
12 try {
13 URL url = new URL(urlPath); // URL对象
14 conn = (HttpURLConnection) url.openConnection(); // 使用URL打开一个链接
15 conn.setDoInput(true); // 允许输入流,即允许下载
16 conn.setDoOutput(true); // 允许输出流,即允许上传
17 conn.setUseCaches(false); // 不使用缓冲
18 conn.setRequestMethod("GET"); // 使用get请求
19 is = conn.getInputStream(); // 获取输入流,此时才真正建立链接
20 InputStreamReader isr = new InputStreamReader(is);
21 BufferedReader bufferReader = new BufferedReader(isr);
22 String inputLine = "";
23 while ((inputLine = bufferReader.readLine()) != null) {
24 resultData += inputLine + "\n";
25 }
26
27 } catch (MalformedURLException e) {
28 // TODO Auto-generated catch block
29 e.printStackTrace();
30 } catch (IOException e) {
31 // TODO Auto-generated catch block
32 e.printStackTrace();
33 } finally {
34 if (is != null) {
35 try {
36 is.close();
37 } catch (IOException e) {
38 // TODO Auto-generated catch block
39 e.printStackTrace();
40 }
41 }
42 if (conn != null) {
43 conn.disconnect();
44 }
45 }
46 Log.i("get", resultData.toString());
47 return resultData;
48 }
49 /***
50 * post请求方式
51 * @param urlPath
52 * @param params
53 * @return
54 */
55 public static String post(String urlPath, Map<String, String> params) {
56 if (params == null || params.size() == 0) {
57 return get(urlPath);
58 }
59 OutputStream os = null;
60 InputStream is = null;
61 HttpURLConnection connection = null;
62 StringBuffer body = getParamString(params);
63 byte[] data = body.toString().getBytes();
64 try {
65 URL url = new URL(urlPath);
66 // 获得URL对象
67 connection = (HttpURLConnection) url.openConnection();
68 // 获得HttpURLConnection对象
69 connection.setRequestMethod("POST");
70 // 设置请求方法为post
71 connection.setUseCaches(false);
72 // 不使用缓存
73 connection.setConnectTimeout(10000);
74 // 设置超时时间
75 connection.setReadTimeout(10000);
76 // 设置读取超时时间
77 connection.setDoInput(true);
78 // 设置是否从httpUrlConnection读入,默认情况下是true;
79 connection.setDoOutput(true);
80 // 设置为true后才能写入参数
81 connection.setRequestProperty("Content-Type",
82 "application/x-www-form-urlencoded");
83 connection.setRequestProperty("Content-Length",
84 String.valueOf(data.length));
85 os = connection.getOutputStream();
86 os.write(data);
87 // 写入参数
88 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
89 // 相应码是否为200
90 is = connection.getInputStream();
91 // 获得输入流
92 BufferedReader reader = new BufferedReader(
93 new InputStreamReader(is));
94 // 包装字节流为字符流
95 StringBuilder response = new StringBuilder();
96 String line;
97 while ((line = reader.readLine()) != null) {
98 response.append(line);
99 }
100 Log.i("post", response.toString());
101 return response.toString();
102 }
103 } catch (Exception e) {
104 e.printStackTrace();
105 } finally {
106 // 关闭
107 if (os != null) {
108 try {
109 os.close();
110 } catch (IOException e) {
111 e.printStackTrace();
112 }
113 }
114 if (is != null) {
115 try {
116 is.close();
117 } catch (IOException e) {
118 e.printStackTrace();
119 }
120 }
121 if (connection != null) {
122 connection.disconnect();
123 connection = null;
124 }
125 }
126 return null;
127 }
128
129 public static StringBuffer getParamString(Map<String, String> params) {
130 StringBuffer result = new StringBuffer();
131 Iterator<Map.Entry<String, String>> iterator = params.entrySet()
132 .iterator();
133 while (iterator.hasNext()) {
134 Map.Entry<String, String> param = iterator.next();
135 String key = param.getKey();
136 String value = param.getValue();
137 result.append(key).append('=').append(value);
138 if (iterator.hasNext()) {
139 result.append('&');
140 }
141 }
142 return result;
143 }
144
145 /**
146 *
147 * 图片加载
148 * @param url
149 * @return
150 */
151 public static Bitmap getImageBitmap(String url) {
152 URL imgUrl = null;
153 Bitmap bitmap = null;
154 try {
155 imgUrl = new URL(url);
156 HttpURLConnection conn = (HttpURLConnection) imgUrl
157 .openConnection();
158 conn.setDoInput(true);
159 conn.connect();
160 InputStream is = conn.getInputStream();
161 bitmap = BitmapFactory.decodeStream(is);
162 is.close();
163 } catch (MalformedURLException e) {
164 // TODO Auto-generated catch block
165 e.printStackTrace();
166 } catch (IOException e) {
167 e.printStackTrace();
168 }
169 return bitmap;
170 }
171
172 }
1 public class MainActivity extends Activity implements OnClickListener {
2 public static String urls = "http://bajie.zhangwoo.cn/app.php?platform=android&appkey=5a379b5eed8aaae531df5f60b12100cfb6dff2c1";
3
4 private TextView mTextView;
5 private ImageView imagegvoew;
6 String resultStr = "";
7 String resultStr1 = "";
8
9 @Override
10 protected void onCreate(Bundle savedInstanceState) {
11 super.onCreate(savedInstanceState);
12 setContentView(R.layout.activity_main);
13 initView();
14 }
15
16 private void initView() {
17 findViewById(R.id.btn1).setOnClickListener(this);
18 findViewById(R.id.btn2).setOnClickListener(this);
19 findViewById(R.id.btn3).setOnClickListener(this);
20 mTextView = (TextView) findViewById(R.id.Text);
21 imagegvoew = (ImageView) findViewById(R.id.imagegvoew);
22
23 }
24
25 @Override
26 public void onClick(View v) {
27 switch (v.getId()) {
28 case R.id.btn1:
29 Thread visitBaiduThread = new Thread(new VisitWebRunnable());
30 visitBaiduThread.start();
31 try {
32 visitBaiduThread.join();
33 if (!resultStr.equals("")) {
34 mTextView.setText(resultStr);
35 }
36 } catch (InterruptedException e) {
37 // TODO Auto-generated catch block
38 e.printStackTrace();
39 }
40 break;
41 case R.id.btn2:
42
43 Thread visitBaiduThreads = new Thread(new VisitWebRunnables());
44 visitBaiduThreads.start();
45 try {
46 visitBaiduThreads.join();
47 if (!resultStr1.equals("")) {
48 mTextView.setText(resultStr1);
49 }
50 } catch (InterruptedException e) {
51 // TODO Auto-generated catch block
52 e.printStackTrace();
53 }
54 break;
55 case R.id.btn3:
56 new Thread(new Runnable() {
57
58 @Override
59 public void run() {
60 // TODO Auto-generated method stub
61 new DownImgAsyncTask()
62 .execute("http://avatar.csdn.net/8/6/0/2_dickyqie.jpg");
63 }
64 }).start();
65
66 break;
67 default:
68 break;
69 }
70
71 }
72
73 class DownImgAsyncTask extends AsyncTask<String, Void, Bitmap> {
74
75 @Override
76 protected void onPreExecute() {
77 // TODO Auto-generated method stub
78 super.onPreExecute();
79
80 }
81
82 @Override
83 protected Bitmap doInBackground(String... params) {
84 // TODO Auto-generated method stub
85 Bitmap b = Util.getImageBitmap(params[0]);
86 return b;
87 }
88
89 @Override
90 protected void onPostExecute(Bitmap result) {
91 // TODO Auto-generated method stub
92 super.onPostExecute(result);
93 if (result != null) {
94 imagegvoew.setImageBitmap(result);
95 }
96 }
97
98 }
99
100 class VisitWebRunnable implements Runnable {
101
102 @Override
103 public void run() {
104 // TODO Auto-generated method stub
105 String data = Util.get(urls);
106 resultStr = data;
107 }
108
109 }
110
111 class VisitWebRunnables implements Runnable {
112
113 @Override
114 public void run() {
115 // TODO Auto-generated method stub
116 Map<String, String> params = new HashMap<String, String>();
117 params.put("q", "test");
118 params.put("showapi_appid", "11548");
119 params.put("showapi_timestamp", "20160511151954");
120 params.put("showapi_sign", "bb1d15ab7ce646ec87cc89d684ca4bcb");
121 String data = Util.post("https://route.showapi.com/32-9", params);
122 resultStr1 = data;
123 }
124
125 }
126 }
· 注意:使用时常出现出现NetworkOnMainThreadException错误,Android.os.NetworkOnMainThreadException错误提示的原因
· 原因:不允许在主线程中进行网络访问
· 解决:将网络访问的操作单独放到一个线程中
记得加网络权限
<uses-permission android:name="android.permission.INTERNET"/>
源码下载:
CSDN:http://download.csdn.net/detail/dickyqie/9701961