android之HttpClient
Apache包是对android联网访问封装的很好的一个包,也是android访问网络最常用的类。
下面分别讲一下怎么用HttpClient实现get,post请求。
1.Get 请求
HttpGet get = new HttpGet("http://www.baidu.com");
HttpClient hClient = new DefaultHttpClient();
httpResponse = hClient.execute(get);
2.Post 请求
Map<String, String> map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
map.put("permission", String.valueOf(permission)); List<NameValuePair> list = new ArrayList<NameValuePair>();
if(map != null && !map.isEmpty()){
for(Map.Entry<String, String> entry : map.entrySet()){//迭代器
//键值对
NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue());
list.add(nameValuePair);
}
} UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list ,encode);
//使用post方式提交数据
HttpPost post = new HttpPost(path);
post.setEntity(entity);//请求体中
//默认客户端
HttpClient client = httpClient; HttpResponse httpResponse = client.execute(post);
3.代码实例:
先是get请求
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; 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.methods.HttpGet;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity { private Button requestButton;
private HttpResponse httpResponse;
private HttpEntity entity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestButton = (Button) findViewById(R.id.requestButton); requestButton.setOnClickListener(new OnClickListener() { public void onClick(View v) {
new Thread(new Downtest()).start();
}
});
}
class Downtest implements Runnable{ public void run() {
//生成一个请求对象,请求
HttpGet get = new HttpGet("http://www.baidu.com");
//生成一个Http客户端对象
HttpClient hClient = new DefaultHttpClient();
//使用Http客户端发送请求对象
InputStream inputStream = null;
try {
httpResponse = hClient.execute(get);//httpResponse返回的响应
//返回的响应数据就放在里边
entity = httpResponse.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line = "";
while((line = reader.readLine())!= null){
result = result+ line;
}
System.out.println(result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
inputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
} }
再是post请求
public class AccountHttpUtils {
//private static String PATH = "http://192.168.253.1:8088/CallName/servlet/AccountServler";
private static HttpClient httpClient;
public AccountHttpUtils(HttpClient httpClient) {
this.httpClient = httpClient;
}
public static String sendHttpClient(String path,Map<String,String> map,String encode){
List<NameValuePair> list = new ArrayList<NameValuePair>();
if(map != null && !map.isEmpty()){
for(Map.Entry<String, String> entry : map.entrySet()){//迭代器
//键值对
NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue());
list.add(nameValuePair);
}
}
try {
//实现将请求的参数封装到表单中,
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list ,encode);
//使用post方式提交数据
HttpPost post = new HttpPost(path);
post.setEntity(entity);//请求体中
//默认客户端
HttpClient client = httpClient;
HttpResponse httpResponse = client.execute(post);
if(httpResponse.getStatusLine().getStatusCode() == 200){
HttpEntity httpEntity = httpResponse.getEntity();
InputStream inputStream = httpEntity.getContent();
return changeInputeStream(inputStream, encode);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* 将一个输入流转换成字符串
* @param inputStream
* @param encode
* @return
*/
private static String changeInputeStream(InputStream inputStream,String encode) {
//通常叫做内存流,写在内存中的
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result = "";
if(inputStream != null){
try {
while((len = inputStream.read(data))!=-1){
data.toString();
outputStream.write(data, 0, len);
}
//result是在服务器端设置的doPost函数中的
result = new String(outputStream.toByteArray(),encode);
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
public static String set(String id,String name,int permission) {
// TODO Auto-generated method stub
Map<String, String> map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
map.put("permission", String.valueOf(permission));
String result = AccountHttpUtils.sendHttpClient(AbstractHttpUtils.PATH+"servlet/AccountServler", map, "utf-8");
System.out.println("result:"+ result);
return result;
}
}
4.get请求访问的是百度,返回的是百度首页的源代码
post是我的一个小项目中的类
不过结构已经很清晰啦。。。。
留着备用。。。。。。
http://www.cnblogs.com/jycboy/p/httpclient.html
android之HttpClient的更多相关文章
- Android 采用HttpClient提交数据到服务器
在前几篇文章中<Android 采用get方式提交数据到服务器><Android 采用post方式提交数据到服务器>介绍了android的两种提交数据到服务器的方法 本文继续介 ...
- android和httpClient
一.说起来都是泪 各大组织不同步,可是我想用别人的库. 二.谷歌和阿帕奇的爱恨情仇 初,谷歌安卓新出,库中自带HttpClient 4.0测试预览版.为与安卓保持API同步,HTTPClient不敢大 ...
- [Android] HttpURLConnection & HttpClient & Socket
Android的三种网络联接方式 1.标准Java接口:java.net.*提供相关的类//定义地址URL url = new URL("http://www.google.com" ...
- android通过HttpClient与服务器JSON交互
通过昨天对HttpClient的学习,今天封装了HttpClient类 代码如下: package com.tp.soft.util; import java.io.BufferedReader; i ...
- android通过httpClient请求获取JSON数据并且解析
使用.net创建一个ashx文件,并response.write json格式 public void ProcessRequest(HttpContext context) { context.R ...
- Android 使用HttpClient方式提交POST请求
final String username = usernameEditText.getText().toString().trim(); final String password = passwr ...
- Android 使用HttpClient方式提交GET请求
public void httpClientGet(View view) { final String username = usernameEditText.getText().toString() ...
- Android采用HttpClient下载图片
在上一章中谈到Android采用HttpURLConnection下载图片,本章使用HttpClient下载图片 HttpURLConnection与HttpClient的差别: HttpClient ...
- Android使用HttpClient向服务器传输文件
HttpClient是Apache Jakarta Common下的子项目,可以用来提供功能丰富的支持HTTP协议的客户端编程工具包,这几天写客户端的时候遇到个问题,“客户端需要向服务器发送Post请 ...
随机推荐
- Windows Azure Virtual Machine (1) IaaS用户手册
<Windows Azure Platform 系列文章目录> Azure IaaS用户手册 - Azure IaaS相关技术- Azure虚拟机成本分析- 创建Azure虚拟机- 使用 ...
- c#实现查询程序运行线程数
class Program { static void Main(string[] args) { List<Thread> list = new List<Thread>() ...
- 前端构建:Less入了个门
一.前言 说到前端构建怎能缺少CSS预处理器呢!其实CSS的预处理器有很多啦,比较出名的有Scss.Sass.Stylus和Less.(最近还听说出现了Autoprefixer等CSS后处理器,可 ...
- View绘制过程理解
假期撸了几篇自定义View相关的东西,后两天下雨呆在家里还是效率太低Orz 每个Activity都包含一个Window对象,这个Window对象通常由PhoneWindow来实现[1],而每个Wi ...
- ES6笔记(3)-- 解构赋值
系列文章 -- ES6笔记系列 解构赋值,即对某种结构进行解析,然后将解析出来的值赋值给相关的变量,常见的有数组.对象.字符串的解构赋值等 一.数组的解构赋值 function ids() { ret ...
- ADO.NET封装的SqlHelper
参照别人的方法,顺便再次复习下ADO.NET的相关知识.为自己的类库做准备. namespace Common.SqlHelper { /// <summary> /// ADO.NET- ...
- .NET Core 调用WCF 服务
.NET Core 和ASP.NET Core 已经可以调用WCF 服务. 环境要求: VS2015 Update 2 +VS2015 Tooling + .NET Core SDK 下载地址: ht ...
- C#自定义特性实例
元数据,就是C#中封装的一些类,无法修改.类成员的特性被称为元数据中的注释. 1.什么是特性 (1)属性与特性的区别 属性(Property):属性是面向对象思想里所说的封装在类里面的数据字段, ...
- springMVC分页,interceptor实现
PageInterceptor.java @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare& ...
- [moka同学笔记]Yii下国家省市三级联动
第一次做省市三级联动时候遇到了坑,感觉还是自己太菜.头疼了很久研究了很久,最后终于发现了问题.大致总结一下思路 在控制器中实例化model,然后在视图中渲染所有国家,当选取国家时候,ajax通过 id ...