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规范参数传递方式,并 ...
随机推荐
- Codeforces Round #290 (Div. 2) C. Fox And Names dfs
C. Fox And Names 题目连接: http://codeforces.com/contest/510/problem/C Description Fox Ciel is going to ...
- GLSL实现HDR Rendering 【转】
http://blog.csdn.net/a3070173/archive/2008/11/29/3408573.aspx HDR - 全称High dynamic rang,是目前流行的3D特效技术 ...
- Mac OS X下高速拷贝文件路径
文件路径表示的是文件在文件系统里的位置,无论是用命令行操作的Linux程序猿还是使用windows的广大用户.都难免会有这种需求 在windows上复制当前文件夹的路径有一个特别方便的方式,仅仅须要用 ...
- VS环境下搭建自己NuGet服务器
一.NuGet服务端的搭建 环境:.NET 4.5 + VS2015 + NuGet.Server 2.10.1 1.建一个空的Web项目,取名叫NuGetServer 2.通过NuGet安装NuGe ...
- HTTP Referer二三事---转
授权方式:署名,非商业用途,保持一致,转载时请务必以超链接(http://www.fwolf.com/blog/post/320)的形式标明文章原始出处和作者信息及本声明. 什么是HTTP Refer ...
- 【PHP代码审计】 那些年我们一起挖掘SQL注入 - 2.全局防护Bypass之UrlDecode
0x01 背景 现在的WEB程序基本都有对SQL注入的全局过滤,像PHP开启了GPC或者在全局文件common.php上使用addslashes()函数对接收的参数进行过滤,尤其是单引号.遇到这种情况 ...
- 关于禁止Android scrollView 因内容变化而自动滚动 android:descendantFocusability
出现这种情况是因为你让scrollview获得了焦点,所以它才会滚动.如果你百度了以后,你可能会发现有些博客会说让焦点停在固定的一个view中就可以了.这对于不存在刷新的页面确实是可以的,但是当你出现 ...
- 亚马逊副总裁谈Marketplace平台的个性化服务
说到个性化,亚马逊无疑是挖掘与利用数据为消费者打造个性化网购体验的先驱之一.而现在,几乎所有的公司和网站都在利用更加个性化的推荐算法为用户提供更好的购物和浏览体验. 亚马逊近年来尤其重视将其个性化特性 ...
- Free download SKP900 update tool & activation tool
One of the SKP900 key programmer user failed to get the SKP900 upgraded and add free tokens online u ...
- WebApi 部署后一直返回404的解决办法
Fixing ASP.NET MVC 4 Web API 404 Posted on November 5, 2012 For a Web Service providing some REST-st ...