简单使用URLConnection、HttpURLConnection和HttpClient访问网络资源
生活随笔
收集整理的這篇文章主要介紹了
简单使用URLConnection、HttpURLConnection和HttpClient访问网络资源
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
URL的openConnection方法將返回一個URLConnection,該對象表示應用程序和URL之間的通信連接。程序可以通過它的實例向該URL發(fā)送請求,讀取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提交則創(chuàng)建HttpGet對象,否則創(chuàng)建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提交則創(chuàng)建HttpGet對象,否則創(chuàng)建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
《新程序員》:云原生和全面數字化實踐50位技術專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的简单使用URLConnection、HttpURLConnection和HttpClient访问网络资源的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 17个提升iOS开发效率的必用工具
- 下一篇: 20个命令行工具监控 Linux 系统性