一:HttpURLConnection简介:

  用于发送或者接受HTTP协议请求的类,获得的数据可以是任意类型和长度,这个类可以用于发送和接收流数据,其长度事先不知道。

  使用这个类遵循一下模式:

  1. 获得一个新的HttpURLConnection通过调用URL.openConnection()获得一个HttpURLConnection实例
  2. 准备请求。请求的主要特性是它的URI。请求头也可以包括元数据,如凭证,首选的内容类型和会话cookie。
  3. 可选择上传请求主体。实例必须配置 setDoOutput(true),如果他们有一个请求主体。以书面形式向被返回的流的getOutputStream.
  4. 读取响应。响应头通常包括元数据,如响应主体的内容类型和长度,修改日期和会话Cookie。响应体可以从返回的流中的getInputStream。如果响应没有主体,该方法返回一个空流。
  5. 断开。一旦响应体已被读取时,HttpURLConnection的应该调用关闭disconnect()。断开释放一个连接持有的资源,所以他们可能被关闭或重新使用。

如下:是通过HttpURLConnection或的数据的例子:

网址url =  new URL ( "http://www.android.com/" );
HttpURLConnection urlConnection = ( HttpURLConnection ) url . openConnection ();
try {
InputStream in = new BufferedInputStream ( urlConnection . getInputStream ());
readStream ( in );
finally {
urlConnection . disconnect ();
}

  HttpURLConnection详细功能,请参照谷歌官方API:http://developer.android.com/reference/java/net/HttpURLConnection.html

  HttpClient简介:

  接口的HTTP客户端。HTTP客户端封装执行HTTP请求,同时处理Cookie,认证,连接管理等功能所需对象的大杂烩。HTTP客户端的线程安全依赖于特定的客户端的实现和配置。

  该类不建议在API22上使用。

  常用的公共方法有:

  1:execute(HttpUriRequest request);     执行使用默认情况下的请求.

  2: getConnectionManager();                获得使用该客户端的连接管理器。

  3: getParams();                                  获得参数,这个用于客户端。

HttpClient这个类比较简单,详细的信息可以参照谷歌官方API:  http://developer.android.com/reference/org/apache/http/client/HttpClient.html

二:通过一个简单的Demo来分别实现HttpURLConnection和HttpClient的GET和POST请求。

  1:Demo展示如下,非常简单:

  2:Activity中代码实现如下:

  (注:因为HTTP网络请求是耗时操作,所以在android开发中,为避免耗时操作阻塞主线程,

   需使用子线程或这一步操作实现这些耗时操作。本例中使用的是AsyncTast异步处理。)

 package activity.cyq.httplearn;

 import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
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 java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button HTTP_GET, HTTP_POST, HTTPClinet_GET, HTTPClient_P0st;
private TextView dataShow;
private final String urlStr = "http://apis.juhe.cn/mobile/get?phone=13429667914&key=a26da09113eaf8bd24456f0bd4037eb3";
private final String urlPost = "http://apis.juhe.cn/mobile/get";
private String phone = "1342966";/*手机号码前七位*/
private final String key = "a26da09113eaf8bd24456f0bd4037eb3"; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); HTTP_GET = (Button) findViewById(R.id.HTTP_GetBTN);
HTTP_POST = (Button) findViewById(R.id.HTTP_PostBTN);
HTTPClinet_GET = (Button) findViewById(R.id.HTTPClient_GetBTN);
HTTPClient_P0st = (Button) findViewById(R.id.HTTPClient_PostBTN);
dataShow = (TextView) findViewById(R.id.dataShowText); HTTP_GET.setOnClickListener(this);
HTTP_POST.setOnClickListener(this);
HTTPClinet_GET.setOnClickListener(this);
HTTPClient_P0st.setOnClickListener(this); } @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.HTTP_GetBTN:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder sBuilder = new StringBuilder();
while ((line = br.readLine()) != null) {
sBuilder.append(line);
}
br.close();
isr.close();
is.close();
return "HTTP_GET请求方式数据结果:" + sBuilder.toString(); } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} @Override
protected void onPostExecute(String s) {
dataShow.append(s);
super.onPostExecute(s);
}
}.execute(urlStr);
break;
case R.id.HTTP_PostBTN:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST");
connection.setReadTimeout(8000);
connection.setConnectTimeout(1000); OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("phone=13429667914&key=a26da09113eaf8bd24456f0bd4037eb3");
bw.close();
osw.close();
os.close(); InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder sBuilder = new StringBuilder();
while ((line = br.readLine()) != null) {
sBuilder.append(line);
}
br.close();
isr.close();
is.close();
return "HTTP_POST请求方式数据结果:" + sBuilder.toString(); } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} @Override
protected void onPostExecute(String s) {
dataShow.append(s);
super.onPostExecute(s);
}
}.execute(urlStr);
break;
case R.id.HTTPClient_GetBTN:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) { HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(params[0]);
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
return result;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
} @Override
protected void onPostExecute(String s) {
dataShow.append("HTTPClient_Get请求方式数据结果:" + s);
super.onPostExecute(s);
} }.execute(urlStr);
break;
case R.id.HTTPClient_PostBTN:
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) { int photoStr = Integer.parseInt(params[1]);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("phone", "13429667914"));
list.add(new BasicNameValuePair("key", "a26da09113eaf8bd24456f0bd4037eb3")); try {
post.setEntity(new UrlEncodedFormEntity(list));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} try {
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
return result;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
} @Override
protected void onPostExecute(String s) {
dataShow.append("HTTPClient_POST请求方式数据结果:" + s);
super.onPostExecute(s);
}
}.execute(urlPost, phone, key);
break; } }
}

HttpURLConnection&HttpClient网络通信的更多相关文章

  1. [Android] HttpURLConnection & HttpClient & Socket

    Android的三种网络联接方式 1.标准Java接口:java.net.*提供相关的类//定义地址URL url = new URL("http://www.google.com" ...

  2. OKHttp源码学习--HttpURLConnection HttpClient OKHttp Get and post Demo用法对比

    1.HttpURLConnection public class HttpURLConnectionGetAndPost { private String urlAddress = "xxx ...

  3. android httpUrlConnection HttpClient

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha httpUrlConnection    超文本传输协议统一资源定位器连接 http 超 ...

  4. 【Cocos2d-x】 HttpClient 网络通信(Http)的简单应用

    Cocos2dx 为我们封装了在cocos2dx中http的网络框架,其文件在cocos2dx引擎包的extensions\network文件下的 HttpClient.HttpRequest .Ht ...

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

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

  6. Android的网络编程

    1.3主要接口 Android平台有三种网络接口可以使用,他们分别是:java.net.*(标准Java接口).Org.apache接口和Android.net.*(Android网络接口).下面分别 ...

  7. android基础(五)网络编程

    android 的网络编程一般可以分为两种:基于Socket的,基于Http的. 一.socket与Http socket封装了TCP/IP协议,TPC/IP协议是传输层协议,主要解决数据如何在网络中 ...

  8. 框架--NoHttp和OkHttp哪个好用,Volley和NoHttp哪个好用?

    NoHttp和OkHttp哪个好用,Volley和NoHttp哪个好用? NoHttp 源码及Demo托管在Github欢迎大家Star: https://github.com/Y0LANDA/NoH ...

  9. 4.2.1 网络请求之HTTP

    HTTP请求&响应:(常用的只有Post与Get,还有Head/put/delete/connect/options/trace) Get&Post(建议用post规范参数传递方式,并 ...

随机推荐

  1. POJ3928、LA4329【树状数组】

    借此题试验一下各种做法的效果~ 这题为ACM2008北京站某题,介于简单与中等之间,做出来,罚时不多基本可以铜了,所以这样的题还必须得会,进阶之路. add(a[i]+1,1)这样处理之后,再用sum ...

  2. ST10 Bootstrap Loader

    Bootstrap Loader The built-in bootstrap loader (BSL) of the ST10F269 provides a mechanism to load th ...

  3. uva539 The Settlers of Catan

    The Settlers of Catan Within Settlers of Catan, the 1995 German game of the year, players attempt to ...

  4. ExtJS和AngularJS比较

    原文地址:http://www.techferry.com/articles/ExtJS-vs-AngularJS.html ExtJS和AngularJS比较.pdf          

  5. 广州项目实施步骤III_练习使用Keepalive保证HaProxy的高可用性

    CentOS6.4 配置HAProxy+Keepalived   安装HAProxy请参考 http://www.cnblogs.com/kgdxpr/p/3272861.html 安装Keepali ...

  6. Java多线程技术学习笔记(二)

    目录: 线程间的通信示例 等待唤醒机制 等待唤醒机制的优化 线程间通信经典问题:多生产者多消费者问题 多生产多消费问题的解决 JDK1.5之后的新加锁方式 多生产多消费问题的新解决办法 sleep和w ...

  7. JavaScript中伪协议 javascript:研究

    将javascript代码添加到客户端的方法是把它放置在伪协议说明符javascript:后的URL中.这个特殊的协议类型声明了URL的主体是任意的javascript代码,它由javascript的 ...

  8. 点击次数(thinkphp)

    protected function addHit($tbName, $id) { //定义变量:作为一个查询条件 $where = array( 'deleted' => 0, 'hidden ...

  9. innobackupex 恢复实验

    [root@localhost backup]# pwd /backup [root@localhost backup]# ll 总用量 drwxr root root Jul : basebacku ...

  10. 如何编写自己的Linux安全检查脚本?

    因为本人工作中要涉及到很多东西,审计(日志.数据神马的).源代码审计.渗透测试.开发一大堆东西,有些东西,越是深入去做,越会发现,没有工具或脚本,工作起来是有多么的坑. 工作的这段时间,自己写了几个工 ...