URL的openConnection方法将返回一个URLConnection,该对象表示应用程序和URL之间的通信连接。程序可以通过它的实例向该URL发送请求,读取URL引用的资源。

下面通过一个简单示例来演示:

Activity:

  1. package com.home.urlconnection;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.net.URLConnection;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10.  
  11. import org.apache.http.HttpEntity;
  12. import org.apache.http.HttpResponse;
  13. import org.apache.http.client.ClientProtocolException;
  14. import org.apache.http.client.HttpClient;
  15. import org.apache.http.client.entity.UrlEncodedFormEntity;
  16. import org.apache.http.client.methods.HttpPost;
  17. import org.apache.http.impl.client.DefaultHttpClient;
  18. import org.apache.http.message.BasicNameValuePair;
  19. import org.apache.http.util.EntityUtils;
  20.  
  21. import android.app.Activity;
  22. import android.os.Bundle;
  23. import android.view.View;
  24. import android.view.View.OnClickListener;
  25. import android.webkit.WebView;
  26. import android.widget.Button;
  27. import android.widget.TextView;
  28.  
  29. public class MainActivity extends Activity implements OnClickListener {
  30. private Button urlConnectionBtn;
  31. private Button httpUrlConnectionBtn;
  32. private Button httpClientBtn;
  33. private TextView showTextView;
  34. private WebView webView;
  35.  
  36. @Override
  37. protected void onCreate(Bundle savedInstanceState) {
  38. super.onCreate(savedInstanceState);
  39. setContentView(R.layout.activity_main);
  40. init();
  41. }
  42.  
  43. private void init() {
  44. urlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_urlconnection);
  45. httpUrlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_httpurlconnection);
  46. httpClientBtn = (Button) findViewById(R.id.test_url_main_btn_httpclient);
  47. showTextView = (TextView) findViewById(R.id.test_url_main_tv_show);
  48. webView = (WebView) findViewById(R.id.test_url_main_wv);
  49. urlConnectionBtn.setOnClickListener(this);
  50. httpUrlConnectionBtn.setOnClickListener(this);
  51. httpClientBtn.setOnClickListener(this);
  52. }
  53.  
  54. @Override
  55. public void onClick(View v) {
  56. if (v == urlConnectionBtn) {
  57. try {
  58. // 直接使用URLConnection对象进行连接
  59. URL url = new URL("http://192.168.1.100:8080/myweb/hello.jsp");
  60. // 得到URLConnection对象
  61. URLConnection connection = url.openConnection();
  62. InputStream is = connection.getInputStream();
  63. byte[] bs = new byte[1024];
  64. int len = 0;
  65. StringBuffer sb = new StringBuffer();
  66. while ((len = is.read(bs)) != -1) {
  67. String str = new String(bs, 0, len);
  68. sb.append(str);
  69. }
  70. showTextView.setText(sb.toString());
  71. } catch (Exception e) {
  72. e.printStackTrace();
  73. }
  74. }
  75. if (v == httpUrlConnectionBtn) {
  76. // 直接使用HttpURLConnection对象进行连接
  77. try {
  78. URL url = new URL(
  79. "http://192.168.1.100:8080/myweb/hello.jsp?username=abc");
  80. // 得到HttpURLConnection对象
  81. HttpURLConnection connection = (HttpURLConnection) url
  82. .openConnection();
  83. // 设置为GET方式
  84. connection.setRequestMethod("GET");
  85. if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
  86. // 得到响应消息
  87. String message = connection.getResponseMessage();
  88. showTextView.setText(message);
  89. }
  90. } catch (Exception e) {
  91. e.printStackTrace();
  92. }
  93. }
  94. if (v == httpClientBtn) {
  95. try {
  96. // 使用ApacheHttp客户端进行连接(重要方法)
  97. HttpClient client = new DefaultHttpClient();
  98.  
  99. // 如果是Get提交则创建HttpGet对象,否则创建HttpPost对象
  100. // POST提交的方式
  101. HttpPost httpPost = new HttpPost(
  102. "http://192.168.1.100:8080/myweb/hello.jsp");
  103. // 如果是Post提交可以将参数封装到集合中传递
  104. List dataList = new ArrayList();
  105. dataList.add(new BasicNameValuePair("username", "abc"));
  106. dataList.add(new BasicNameValuePair("pwd", "123"));
  107. // UrlEncodedFormEntity用于将集合转换为Entity对象
  108. httpPost.setEntity(new UrlEncodedFormEntity(dataList));
  109.  
  110. // GET提交的方式
  111. // HttpGet httpGet = new
  112. // HttpGet("http://192.168.1.100:8080/myweb/hello.jsp?username=abc&pwd=321");
  113.  
  114. // 获取相应消息
  115. HttpResponse httpResponse = client.execute(httpPost);
  116. // 获取消息内容
  117. HttpEntity entity = httpResponse.getEntity();
  118. // 把消息对象直接转换为字符串
  119. String content = EntityUtils.toString(entity);
  120. // 显示在TextView中
  121. // showTextView.setText(content);
  122.  
  123. // 通过webview来解析网页
  124. webView.loadDataWithBaseURL(null, content, "text/html",
  125. "utf-8", null);
  126. // 直接根据url来进行解析
  127. // webView.loadUrl(url);
  128. } catch (ClientProtocolException e) {
  129. e.printStackTrace();
  130. } catch (IOException e) {
  131. e.printStackTrace();
  132. }
  133. }
  134. }
  135.  
  136. }

上面使用到的url是部署在笔者本机的web应用,这里不再给出,大家可以换成自己的web应用即可。
布局XML:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6.  
  7. <Button
  8. android:id="@+id/test_url_main_btn_urlconnection"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:text="使用URLConnection连接" />
  12.  
  13. <Button
  14. android:id="@+id/test_url_main_btn_httpurlconnection"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:text="使用HttpURLConnection连接" />
  18.  
  19. <Button
  20. android:id="@+id/test_url_main_btn_httpclient"
  21. android:layout_width="wrap_content"
  22. android:layout_height="wrap_content"
  23. android:text="使用Apache客户端连接" />
  24.  
  25. <TextView
  26. android:id="@+id/test_url_main_tv_show"
  27. android:layout_width="wrap_content"
  28. android:layout_height="wrap_content" />
  29.  
  30. <WebView
  31. android:id="@+id/test_url_main_wv"
  32. android:layout_width="match_parent"
  33. android:layout_height="match_parent" />
  34.  
  35. </LinearLayout>

权限:

  1. <uses-permission android:name="android.permission.INTERNET" />

简单使用URLConnection、HttpURLConnection和HttpClient访问网络资源的更多相关文章

  1. HTTP访问的两种方式:HttpURLConnection和HTTPClient的比较

    http://blog.sina.com.cn/s/blog_87216a0001014sm7.html http://www.2cto.com/kf/201305/208770.html ----- ...

  2. [转]Android访问网络,使用HttpURLConnection还是HttpClient

    转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/12452307 最近在研究Volley框架的源码,发现它在HTTP请求的使用上比较有 ...

  3. crawler_基础之_java.net.HttpURLConnection 访问网络资源

    java访问网络资源 由底层到封装  为  scoket==> java.net.HttpURLConnection==>HttpClient 这次阐述先 java.net.HttpURL ...

  4. Android访问网络,使用HttpURLConnection还是HttpClient?

    本文转自:http://blog.csdn.net/guolin_blog/article/details/12452307,感谢这位网友的分享,谢谢. 最近在研究Volley框架的源码,发现它在HT ...

  5. HttpURLConnection与HttpClient浅析

    转自:https://blog.csdn.net/u012838207/article/details/82867701 HttpURLConnection与HttpClient浅析 1. GET请求 ...

  6. HttpURLConnection与HttpClient比较和使用示例

    1. GET请求与POST请求 HTTP协议是现在Internet上使用得最多.最重要的协议了,越来越多的Java应用程序需要直接通过HTTP协议来访问网络资源. 在介绍HttpURLConnecti ...

  7. HttpURLConnection与HttpClient随笔

    目前在工作中遇到的需要各种对接接口的工作,需要用到HTTP的知识,工作完成后想要做一些笔记,本来知识打算把自己写的代码粘贴上来就好了,但是偶然发现一篇博文对这些知识的总结非常到位,自认无法写的这么好, ...

  8. HttpURLConnection和HttpClient的区别(转)

    HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.在 JDK 的 java.net 包中已经提供了访问 ...

  9. HttpURLConnection与HttpClient浅析---转

    HttpURLConnection与HttpClient浅析 1. GET请求与POST请求 HTTP协议是现在Internet上使用得最多.最重要的协议了,越来越多的Java应用程序需要直接通过HT ...

随机推荐

  1. POJ3233(矩阵二分再二分)

    题目非常有简单: Description Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + ...

  2. 安卓MonkeyRunner源码分析之与Android设备通讯方式

    如前文<谁动了我的截图?--Monkeyrunner takeSnapshot方法源码跟踪分析>所述,本文主要会尝试描述android的自动化测试框架MonkeyRunner究竟是如何和目 ...

  3. Java替换字符或十进制数的字符串

    如今,这个项目的需求:将"甲状腺结节 5*3 cm" 更换 "甲状腺结节 * cm". 在一个字符串的数字来替换空白. 码,如以下: public static ...

  4. 分布式消息系统kafka

    kafka:一个分布式消息系统 1.背景 最近因为工作需要,调研了追求高吞吐的轻量级消息系统Kafka,打算替换掉线上运行的ActiveMQ,主要是因为明年的预算日流量有十亿,而ActiveMQ的分布 ...

  5. Oracle SqlPlus 方向键的方法和解决的退格键失效

    SqlPlus中退格键和方向键的设置 在刚装好的Oracle中,我们使用SqlPlus会发现很的蹩脚,不仅退格键不好用,方向键也不行调出history.以下有几种解决方法. 1.能够使用ctrl+Ba ...

  6. OpenStreetMap架构

    OpenStreetMap框架简介 1.OSM平台开发 OpenStreetMap(缩写OSM)地图是一个合作项目,我们的目标是创建一个免费的内容,让所有的人都可以编辑的世界地图. OSM在地图上由一 ...

  7. View中的Razor使用

    View中的Razor使用   上一节:ASP.NET MVC5 + EF6 入门教程 (5) Model和Entity Framework 源码下载:点我下载 一.Razor简介 在解决方案资源管理 ...

  8. Url.Content

    Url.Content了,Url是ViewPage的一个对象,它最常用的一个方法就是Content,它的功能是返回某个文件的路径.一般情况下,在使用了ASP.NET MVC后,目录结构变得有点诡异,像 ...

  9. Windows在结构FTPserver

    同Windows8 案件,结构介绍 FTPserver脚步: 1.为Windows开启FTP功能:控制面板->程序->启用或关闭Windows功能.将下图所看到的的复选框选中 waterm ...

  10. Zend Server更新至6.2版本——虚拟主机全方位管理

    Zend Server自从发布6.0以来,并支持云服务,成为很多PHP程序所选择的Web服务器. Zend Server 6.2版本从更新内容来看,解决了Web服务器与虚拟主机之间的协同管理.并在细节 ...