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

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

Activity:

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:

<?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>

权限:

 <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. android 控制手机的体积的大小 切换音效模式

    (1)项目介绍 于android API的AudioManager于,它提供了一种方法来调整电话音量. audioMa.adjustVolume(AudioManager.ADJUST_LOWER, ...

  2. 从.net复制源代码中国农历阵列,必要做日历

    从.net复制源代码中国农历阵列,必要做日历 const { 闰月的月份.春节的阳历日期(农历正月初一).农历的每一个月天数 } c_arrLunarInfo: array [1900 .. 2100 ...

  3. AutoCAD 2012安装错误,与.net framework (1603错误)以及ms2005vc++的问题。

    首先,这是AutoCAD2012的问题.因为,如果一台计算机已经安装了这些软件,AutoCAD是无法识别出来,因此AutoCAD就只能报错.正确的做法是:如果检测到这些软件已经被安装,则需要忽略这些问 ...

  4. flash导入图片缩放后出现毛边、失真、锯齿、文字模糊不清晰的情况

    原因: 1.flash的性能非常差,这就不得不让它做大量的优化. 2.图片缩放,目前业界有多种算法,画质越好的算法,计算量越大. 3.flash优化了图片缩放,使用了质量非常低的缩放算法.这个做法,保 ...

  5. ExtJs--12--Ext定义类的requires uses singleton 三个配置项的使用

    Ext.onReady(function(){ /* * requires uses singleton 三个配置项的使用 */ Ext.define("A",{ //requir ...

  6. 使用SQL Server 2005数据库管理工具 - 初学者系列 - 学习者系列文章

    本文讲述使用SQL Server 2005 Express数据库管理工具的使用. 1.打开数据库管理工具 2.选择下面的SQL Server 身份验证,因为在安装数据库的时候设置了sa的密码. 3.选 ...

  7. android shape总结 和控制的风格定制

    1:shape总结 1):shape文件是放置在drawable文件下的.res/drawable/filename.xml. 2):shape类型:android:shape. 一共同拥有四种:re ...

  8. Win7下Redmine2.0.3+Mysql55+Ruby1.8.7成功安装记录分享

    准备软件: Ruby 下载网页: http://rubyforge.org/frs/?group_id=167&release_id=46836 http://files.rubyforge. ...

  9. ef左联三张表案例

    users:用户表 Orderss:订单表 U_O:用户和订单的中间表 OrdersEntities1 oe = new OrdersEntities1();            var resul ...

  10. 数据结构栈的java实现

    近来复习数据结构,自己动手实现了栈.栈是一种限制插入和删除只能在一个位置上的表.最基本的操作是进栈和出栈,因此,又被叫作“先进后出”表. 实现方式是这样的:首先定义了一个接口,然后通过这个接口实现了线 ...