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的更多相关文章

  1. Android 采用HttpClient提交数据到服务器

    在前几篇文章中<Android 采用get方式提交数据到服务器><Android 采用post方式提交数据到服务器>介绍了android的两种提交数据到服务器的方法 本文继续介 ...

  2. android和httpClient

    一.说起来都是泪 各大组织不同步,可是我想用别人的库. 二.谷歌和阿帕奇的爱恨情仇 初,谷歌安卓新出,库中自带HttpClient 4.0测试预览版.为与安卓保持API同步,HTTPClient不敢大 ...

  3. [Android] HttpURLConnection & HttpClient & Socket

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

  4. android通过HttpClient与服务器JSON交互

    通过昨天对HttpClient的学习,今天封装了HttpClient类 代码如下: package com.tp.soft.util; import java.io.BufferedReader; i ...

  5. android通过httpClient请求获取JSON数据并且解析

    使用.net创建一个ashx文件,并response.write  json格式 public void ProcessRequest(HttpContext context) { context.R ...

  6. Android 使用HttpClient方式提交POST请求

    final String username = usernameEditText.getText().toString().trim(); final String password = passwr ...

  7. Android 使用HttpClient方式提交GET请求

    public void httpClientGet(View view) { final String username = usernameEditText.getText().toString() ...

  8. Android采用HttpClient下载图片

    在上一章中谈到Android采用HttpURLConnection下载图片,本章使用HttpClient下载图片 HttpURLConnection与HttpClient的差别: HttpClient ...

  9. Android使用HttpClient向服务器传输文件

    HttpClient是Apache Jakarta Common下的子项目,可以用来提供功能丰富的支持HTTP协议的客户端编程工具包,这几天写客户端的时候遇到个问题,“客户端需要向服务器发送Post请 ...

随机推荐

  1. asp.net中打印指定控件内容

    1.写一个PrintHelper类using System;using System.Data;using System.Configuration;using System.Web;using Sy ...

  2. [New Portal]Windows Azure Virtual Machine (15) 在本地制作数据文件VHD并上传至Azure(2)

    <Windows Azure Platform 系列文章目录> 在上一章内容里,我们已经将包含有OFFICE2013 ISO安装文件的VHD上传至Azure Blob Storage中了. ...

  3. caffe-window搭建自己的小项目例子

    手头有一个实际的视觉检测的项目,用的是caffe来分类,于是需要用caffe新建自己的项目的例子.在网上找了好久都没有找到合适的,于是自己开始弄. 1 首先是配置caffe的VC++目录中的inclu ...

  4. 关于Entity Framework采用DB First模式创建后的实体批量修改相关属性技巧

    Entity Framework采用DB First模式创建实体是比较容易与方便的,修改已创建的实体在个数不多的情况下也是没问题的,但如果已创建的实体比较多,比如10个实体以上,涉及修改的地方比较多的 ...

  5. 【Swift学习】Swift编程之旅---ARC(二十)

    Swift使用自动引用计数(ARC)来跟踪并管理应用使用的内存.大部分情况下,这意味着在Swift语言中,内存管理"仍然工作",不需要自己去考虑内存管理的事情.当实例不再被使用时, ...

  6. PHP开发知识

    基本职能 服务器端开发-PHP,主要使用语言是PHP,主要是服务端工程师. 具体要求 对PHP达到熟悉的程度:熟读PHP手册,掌握开发的小技巧. 学习和研究PHP内核. 设计模式,缓存,存储 深远价值 ...

  7. 从零开始学习jQuery (一) 入门篇

    本系列文章导航 从零开始学习jQuery (一) 入门篇 一.摘要 本系列文章将带您进入jQuery的精彩世界, 其中有很多作者具体的使用经验和解决方案,  即使你会使用jQuery也能在阅读中发现些 ...

  8. MVC EF中Attach和Entry区别

    EF:加入容器三种方式-->查询,attach,entry.不在容器里,不能用remove,add等方法. 1.0 使用Attach可能会出错.//attach 意思:附上; 贴上,系;var ...

  9. RAID一个硬盘FAIL。

    周六本想清静学习一下,刚把咖啡冲好还没有来得及坐下,机房却传来让人心揪的报警声,原来一台服务器一个硬盘FAIL(挂了...... 抽换好的一个容量大小的SCSI硬盘,再次进入这个介面,选择Force ...

  10. Bootstrap学习笔记系列5------Bootstrap图片显示

    通过添加一下的class来实现bootstrap对图片的支持 img-round 通过border-radius:6px 来获得图片圆角 img-circle 通过border-radius:50%来 ...