一: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. jquery调用页面的方法

    本文转载:http://www.cnblogs.com/chenxizhang/archive/2009/05/28/1491250.html 有些朋友问到,能不能在jquery代码中调用后台cs页面 ...

  2. 新浪微博SSO登陆机制

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...

  3. 从零开始学android开发-项目重命名

    --修改项目名称 选中项目-[refactor]-[rename] --修改package名称 选中需要重命名的包-[refactor]-[rename] --修改gen下面的名称 打开Android ...

  4. C++ Interview - using new and delete to alloc and free memory

    1. dynamic create object and initialization int *pi = new int; // pi points to an uninitialized int ...

  5. Codeforces Round #340 (Div. 2) E. XOR and Favorite Number 莫队算法

    E. XOR and Favorite Number 题目连接: http://www.codeforces.com/contest/617/problem/E Descriptionww.co Bo ...

  6. UVA 1069 - Always an integer(数论)

    1069 - Always an integer 题意:给定一个多项式,推断是否总是整数 思路:LRJ大白上的例题,上面给出了证明,仅仅要1到k + 1(k为最高次数)带入方程都是整数,那么整个方程就 ...

  7. opengl之vsh、fsh简易介绍+cocos2dx 3.0 shader 变灰

    认识着色器 理解OpenGL渲染管线,对于学习OpenGL非常重要.下面是OpenGL渲染管线的示意图:(图中淡蓝色区域是可以编程的阶段) 此图是从wiki中拿过来的,OpenGL的渲染管线主要包括: ...

  8. SecureCRT 滚动条设置

    不久前在Debian下使用kermit时发现kermit有一些优点,比如当串口上不断有信息打印时,仍然可以通过拖动滚动条来查看以前打印的信息,并且滚动条不会滚动到最下面.当按下回车键时,滚动条会自动滚 ...

  9. jquery操作cookie {分享}

    web开发过程中如果网站有一部分信息是存储在cookie中并与服务器交互的话,那么前台有时就会遇到需要对cookie中信息进行操作的情况,一个最典型的例子就是在前台判断用户是否登录过当前所访问的网站. ...

  10. org.apache.hadoop.conf-Configured

    org.apache.hadoop.conf中的最后一个类,也是这个包中以后用的最频繁的一个,Configurable算是肉体,Configuration算是灵魂吧 package org.apach ...