本文主要是介绍简单使用URLConnection、HttpURLConnection和HttpClient访问网络资源,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
随时随地技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)
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;@Overrideprotected 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);}@Overridepublic 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" ><Buttonandroid:id="@+id/test_url_main_btn_urlconnection"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="使用URLConnection连接" /><Buttonandroid:id="@+id/test_url_main_btn_httpurlconnection"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="使用HttpURLConnection连接" /><Buttonandroid:id="@+id/test_url_main_btn_httpclient"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="使用Apache客户端连接" /><TextViewandroid:id="@+id/test_url_main_tv_show"android:layout_width="wrap_content"android:layout_height="wrap_content" /><WebViewandroid: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访问网络资源的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!