欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

简单使用URLConnection、HttpURLConnection和HttpClient访问网络资源

发布时间:2025/5/22 编程问答 49 豆豆
生活随笔 收集整理的这篇文章主要介绍了 简单使用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

《新程序员》:云原生和全面数字化实践50位技术专家共同创作,文字、视频、音频交互阅读

总结

以上是生活随笔为你收集整理的简单使用URLConnection、HttpURLConnection和HttpClient访问网络资源的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。