简单使用URLConnection、HttpURLConnection和HttpClient访问网络资源
URL的openConnection方法将返回一个URLConnection,该对象表示应用程序和URL之间的通信连接。程序可以通过它的实例向该URL发送请求,读取URL引用的资源。
下面通过一个简单示例来演示:
Activity:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
|
package com.home.urlconnection;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private Button urlConnectionBtn;
private Button httpUrlConnectionBtn;
private Button httpClientBtn;
private TextView showTextView;
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
urlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_urlconnection);
httpUrlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_httpurlconnection);
httpClientBtn = (Button) findViewById(R.id.test_url_main_btn_httpclient);
showTextView = (TextView) findViewById(R.id.test_url_main_tv_show);
webView = (WebView) findViewById(R.id.test_url_main_wv);
urlConnectionBtn.setOnClickListener( this );
httpUrlConnectionBtn.setOnClickListener( this );
httpClientBtn.setOnClickListener( this );
}
@Override
public void onClick(View v) {
if (v == urlConnectionBtn) {
try {
// 直接使用URLConnection对象进行连接
URL url = new URL( "http://192.168.1.100:8080/myweb/hello.jsp" );
// 得到URLConnection对象
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
byte [] bs = new byte [ 1024 ];
int len = 0 ;
StringBuffer sb = new StringBuffer();
while ((len = is.read(bs)) != - 1 ) {
String str = new String(bs, 0 , len);
sb.append(str);
}
showTextView.setText(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
if (v == httpUrlConnectionBtn) {
// 直接使用HttpURLConnection对象进行连接
try {
URL url = new URL(
"http://192.168.1.100:8080/myweb/hello.jsp?username=abc" );
// 得到HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// 设置为GET方式
connection.setRequestMethod( "GET" );
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// 得到响应消息
String message = connection.getResponseMessage();
showTextView.setText(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (v == httpClientBtn) {
try {
// 使用ApacheHttp客户端进行连接(重要方法)
HttpClient client = new DefaultHttpClient();
// 如果是Get提交则创建HttpGet对象,否则创建HttpPost对象
// POST提交的方式
HttpPost httpPost = new HttpPost(
"http://192.168.1.100:8080/myweb/hello.jsp" );
// 如果是Post提交可以将参数封装到集合中传递
List dataList = new ArrayList();
dataList.add( new BasicNameValuePair( "username" , "abc" ));
dataList.add( new BasicNameValuePair( "pwd" , "123" ));
// UrlEncodedFormEntity用于将集合转换为Entity对象
httpPost.setEntity( new UrlEncodedFormEntity(dataList));
// GET提交的方式
// HttpGet httpGet = new
// HttpGet("http://192.168.1.100:8080/myweb/hello.jsp?username=abc&pwd=321");
// 获取相应消息
HttpResponse httpResponse = client.execute(httpPost);
// 获取消息内容
HttpEntity entity = httpResponse.getEntity();
// 把消息对象直接转换为字符串
String content = EntityUtils.toString(entity);
// 显示在TextView中
// showTextView.setText(content);
// 通过webview来解析网页
webView.loadDataWithBaseURL( null , content, "text/html" ,
"utf-8" , null );
// 直接根据url来进行解析
// webView.loadUrl(url);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.home.urlconnection;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private Button urlConnectionBtn;
private Button httpUrlConnectionBtn;
private Button httpClientBtn;
private TextView showTextView;
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
urlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_urlconnection);
httpUrlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_httpurlconnection);
httpClientBtn = (Button) findViewById(R.id.test_url_main_btn_httpclient);
showTextView = (TextView) findViewById(R.id.test_url_main_tv_show);
webView = (WebView) findViewById(R.id.test_url_main_wv);
urlConnectionBtn.setOnClickListener( this );
httpUrlConnectionBtn.setOnClickListener( this );
httpClientBtn.setOnClickListener( this );
}
@Override
public void onClick(View v) {
if (v == urlConnectionBtn) {
try {
// 直接使用URLConnection对象进行连接
URL url = new URL( "http://192.168.1.100:8080/myweb/hello.jsp" );
// 得到URLConnection对象
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
byte [] bs = new byte [ 1024 ];
int len = 0 ;
StringBuffer sb = new StringBuffer();
while ((len = is.read(bs)) != - 1 ) {
String str = new String(bs, 0 , len);
sb.append(str);
}
showTextView.setText(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
if (v == httpUrlConnectionBtn) {
// 直接使用HttpURLConnection对象进行连接
try {
URL url = new URL(
"http://192.168.1.100:8080/myweb/hello.jsp?username=abc" );
// 得到HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// 设置为GET方式
connection.setRequestMethod( "GET" );
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// 得到响应消息
String message = connection.getResponseMessage();
showTextView.setText(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (v == httpClientBtn) {
try {
// 使用ApacheHttp客户端进行连接(重要方法)
HttpClient client = new DefaultHttpClient();
// 如果是Get提交则创建HttpGet对象,否则创建HttpPost对象
// POST提交的方式
HttpPost httpPost = new HttpPost(
"http://192.168.1.100:8080/myweb/hello.jsp" );
// 如果是Post提交可以将参数封装到集合中传递
List dataList = new ArrayList();
dataList.add( new BasicNameValuePair( "username" , "abc" ));
dataList.add( new BasicNameValuePair( "pwd" , "123" ));
// UrlEncodedFormEntity用于将集合转换为Entity对象
httpPost.setEntity( new UrlEncodedFormEntity(dataList));
// GET提交的方式
// HttpGet httpGet = new
// HttpGet("http://192.168.1.100:8080/myweb/hello.jsp?username=abc&pwd=321");
// 获取相应消息
HttpResponse httpResponse = client.execute(httpPost);
// 获取消息内容
HttpEntity entity = httpResponse.getEntity();
// 把消息对象直接转换为字符串
String content = EntityUtils.toString(entity);
// 显示在TextView中
// showTextView.setText(content);
// 通过webview来解析网页
webView.loadDataWithBaseURL( null , content, "text/html" ,
"utf-8" , null );
// 直接根据url来进行解析
// webView.loadUrl(url);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
上面使用到的url是部署在笔者本机的web应用,这里不再给出,大家可以换成自己的web应用即可。
布局XML:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
<? xml version = "1.0" encoding = "utf-8" ?>
< LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical" >
< Button
android:id = "@+id/test_url_main_btn_urlconnection"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "使用URLConnection连接" />
< Button
android:id = "@+id/test_url_main_btn_httpurlconnection"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "使用HttpURLConnection连接" />
< Button
android:id = "@+id/test_url_main_btn_httpclient"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "使用Apache客户端连接" />
< TextView
android:id = "@+id/test_url_main_tv_show"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
< WebView
android:id = "@+id/test_url_main_wv"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</ LinearLayout >
<? xml version = "1.0" encoding = "utf-8" ?>
< LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical" >
< Button
android:id = "@+id/test_url_main_btn_urlconnection"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "使用URLConnection连接" />
< Button
android:id = "@+id/test_url_main_btn_httpurlconnection"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "使用HttpURLConnection连接" />
< Button
android:id = "@+id/test_url_main_btn_httpclient"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "使用Apache客户端连接" />
< TextView
android:id = "@+id/test_url_main_tv_show"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
< WebView
android:id = "@+id/test_url_main_wv"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</ LinearLayout >
|
权限:
1
2
3
4
5
|
< uses-permission android:name = "android.permission.INTERNET" />
< uses-permission android:name = "android.permission.INTERNET" />
|
转载于:https://www.cnblogs.com/AceIsSunshineRain/p/5095114.html
简单使用URLConnection、HttpURLConnection和HttpClient访问网络资源相关推荐
- android系统提供了url通信,Android两种HTTP通信,HttpURLConnection和HttpClient
Android系统中主要提供了两种方式来进行HTTP通信,HttpURLConnection和HttpClient,几乎在任何项目的代码中我们都能看到这两个类的身影,使用率非常高. 不过HttpURL ...
- Android之访问网络,使用HttpURLConnection还是HttpClient?
<span style="font-family: Arial; font-size: 14px; background-color: rgb(255, 255, 255);" ...
- HttpURLConnection与HttpClient浅析---转
HttpURLConnection与HttpClient浅析 1. GET请求与POST请求 HTTP协议是现在Internet上使用得最多.最重要的协议了,越来越多的Java应用程序需要直接通过HT ...
- (转)HttpURLConnection与 HttpClient 区别
转自: HttpURLConnection与 HttpClient 区别/性能测试对比 - 尚码园HttpURLConnection与HttpClient随笔 目前在工做中遇到的须要各类对接接口的工做 ...
- Android访问网络资源
Android访问网络资源 当我们写AndroidAPP的时候,一定会考虑一个很重要的问题,那就是如何让APP能调用网上的其他资源呢?这时候就需要用到URL(Uniform Resource Loca ...
- HttpUrlConnection与HttpClient的认识(六) -实际应用之刷网络流量
既然已经上面几章学到了通过HttpUrlConnection和HttpClient发送网络请求,我们可以获取到网络的响应,其实我们上面的例子可以说是一个简单的爬虫啊,把一个Url的网页内容全部下载下来 ...
- Android开发之使用URL访问网络资源
Android开发之使用URL访问网络资源 URL (UniformResource Locator)对象代表统一资源定位器,它是指向互联网"资源"的指针.资源可以是简单的文件或目 ...
- 使用HttpClient访问WEB资源
虽然在 JDK 的 java.net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 本身提供的功能还不够丰富和灵活.HttpClient 是Apache Jakart ...
- HttpURLConnection及HttpClient选择(转)
介绍Android中Http请求方式的选择.区别及几个常用框架对API的选择 1. 两种请求方式对比 Android Http请求API主要分两种: 第一种是Java的HttpURLConnectio ...
最新文章
- [Big Data - Kafka] kafka学习笔记:知识点整理
- 第二十八课.AlphaGo实例分析
- 【Android FFMPEG 开发】Android Studio 中 配置 FFMPEG 库最小兼容版本 ( undefined reference to 'atof' )
- c语言long long类型赋值
- 使用线程新建WPF窗体(公用进度条窗体)
- Hadoop工具如何形成SAP Hana的大数据平台
- 职场健康:缓解脖子酸
- WCF服务编程 学习笔记(2)
- 删除文件夹里的图片,打印删除日志
- python实现雪花飘落的效果_使用javascript实现雪花飘落的效果
- tomcat以debug模式启动
- hadoop基础【Shuffle全部流程、OutputFormat输出、ReduceJoin案例实操】
- python输入整数反转输出_7. 整数反转(Python)
- 超市火灾烟气蔓延及人员疏散的matlab仿真模拟
- JAVA多态的理解及应用
- Linux基本操作1
- 【实用】OS X Lion restore Recovery HD Manually 手工创建 OS X Lion 恢复分区
- C#生成含数字字母的随机字符串
- 传奇私服游戏支付接口申请(已解决)
- 给公司代码分配销售组织