HttpURLConnection&HttpClient网络通信
一:HttpURLConnection简介:
用于发送或者接受HTTP协议请求的类,获得的数据可以是任意类型和长度,这个类可以用于发送和接收流数据,其长度事先不知道。
使用这个类遵循一下模式:
- 获得一个新
的HttpURLConnection
通过调用URL.openConnection()
获得一个HttpURLConnection实例
。 - 准备请求。请求的主要特性是它的URI。请求头也可以包括元数据,如凭证,首选的内容类型和会话cookie。
- 可选择上传请求主体。实例必须配置
setDoOutput(true)
,如果他们有一个请求主体。以书面形式向被返回的流的
getOutputStream.
- 读取响应。响应头通常包括元数据,如响应主体的内容类型和长度,修改日期和会话Cookie。响应体可以从返回的流中
的getInputStream
。如果响应没有主体,该方法返回一个空流。 - 断开。一旦响应体已被读取时,
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网络通信的更多相关文章
- [Android] HttpURLConnection & HttpClient & Socket
Android的三种网络联接方式 1.标准Java接口:java.net.*提供相关的类//定义地址URL url = new URL("http://www.google.com" ...
- OKHttp源码学习--HttpURLConnection HttpClient OKHttp Get and post Demo用法对比
1.HttpURLConnection public class HttpURLConnectionGetAndPost { private String urlAddress = "xxx ...
- android httpUrlConnection HttpClient
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha httpUrlConnection 超文本传输协议统一资源定位器连接 http 超 ...
- 【Cocos2d-x】 HttpClient 网络通信(Http)的简单应用
Cocos2dx 为我们封装了在cocos2dx中http的网络框架,其文件在cocos2dx引擎包的extensions\network文件下的 HttpClient.HttpRequest .Ht ...
- crawler_基础之_java.net.HttpURLConnection 访问网络资源
java访问网络资源 由底层到封装 为 scoket==> java.net.HttpURLConnection==>HttpClient 这次阐述先 java.net.HttpURL ...
- Android的网络编程
1.3主要接口 Android平台有三种网络接口可以使用,他们分别是:java.net.*(标准Java接口).Org.apache接口和Android.net.*(Android网络接口).下面分别 ...
- android基础(五)网络编程
android 的网络编程一般可以分为两种:基于Socket的,基于Http的. 一.socket与Http socket封装了TCP/IP协议,TPC/IP协议是传输层协议,主要解决数据如何在网络中 ...
- 框架--NoHttp和OkHttp哪个好用,Volley和NoHttp哪个好用?
NoHttp和OkHttp哪个好用,Volley和NoHttp哪个好用? NoHttp 源码及Demo托管在Github欢迎大家Star: https://github.com/Y0LANDA/NoH ...
- 4.2.1 网络请求之HTTP
HTTP请求&响应:(常用的只有Post与Get,还有Head/put/delete/connect/options/trace) Get&Post(建议用post规范参数传递方式,并 ...
随机推荐
- java面试笔试试题http://www.jobui.com/mianshiti/it/java/6827/
一.判断题(每题1分,共10分)1.Applet是一种特殊的Panel,它是Java Applet程序的最外层容器.()2.Java的源代码中定义几个类,编译结果就生成几个以.class为后缀的字节码 ...
- 数据结构复习:直接插入排序与二分插入排序的C++实现
1.直接插入排序 直接插入排序的过程可以理解为一个固定长度的数组被分为两个集合,即已排序集合和未排序. 开始时已排序集合为空,而未排序集合即为整个数组.当排序开始后插入一个对象,已排序集合元素数目加1 ...
- Codeforces Gym 100015C City Driving 离线LCA
City Driving 题目连接: http://codeforces.com/gym/100015/attachments Description You recently started fre ...
- 如何在C#中使用全局鼠标、键盘Hook
今天,有个同事问我,怎样在C#中使用全局钩子?以前写的全局钩子都是用unmanaged C或C++写个DLL来实现,可大家都知道,C#是基于.Net Framework的,是managed,怎么实现全 ...
- thinkphp关联查询
$list=$model->table("$dName d ,$mName m,$cName c") ->field('d.*,m.title as musicTitl ...
- A. Fox and Box Accumulation
time limit per test 1 second memory limit per test 256 megabytes input standard input output standar ...
- GPS获取Location 获取所在地点的经纬度
利用手机获取所在地点的经纬度: Location 在Android 开发中还是经常用到的,比如 通过经纬度获取天气,根据Location 获取所在地区详细Address (比如Google Map 开 ...
- 【JavsScript】一个元素绑定多个事件
<script> document.getElementById("a").addEventListener("click", function() ...
- iOS开发——实用技术OC篇&简单抽屉效果的实现
简单抽屉效果的实现 就目前大部分App来说基本上都有关于抽屉效果的实现,比如QQ/微信等.所以,今天我们就来简单的实现一下.当然如果你想你的效果更好或者是封装成一个到哪里都能用的工具类,那就还需要下一 ...
- javascript 拷贝
拷贝简单分为浅拷贝与深度拷贝,即给定一个对象,生成一个相同的对象. 浅拷贝 function copy(source,destiny){ destiny = destiny || {}; if(typ ...