android http处理

用到的类:

包:org.apache.http

 

1、HttpClient

2、HttpResponse

3、HttpStatus

4、HttpGet     HttpUriRequest

5、HttpPost   HttpUriRequest

6、NameValuePair  BasicNameValuePair

7、HttpEntity      UrlEncodedFormEntity

8、EntityUtils

 

包:java.net.URLEncoder

1、URLEncoder


示例代码:



/*
* author   : sunyimin
* time     : 2012.3.8 22:50
* describe : android http  get/post 交互
*/

//需导入的包
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

//Get
void Get(String url, Map<String, String> messages) {
	String params = "";  //请求参数
	String result = "";  //结果
	try {
		//转码
		for (Map.Entry<String, String> pair : messages.entrySet()) {
			String encodedValues = URLEncoder.encode(pair.getValue(), "utf8");
			params += "&" + pair.getKey() + "=" + encodedValues;
		}
	} catch(Exception e) {
		e.printStackTrace();
	}
	
	try {
		HttpGet request = new HttpGet(url);
		HttpClient client = new DefaultHttpClient();
		HttpResponse response = client.execute(request);
		if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			result = EntityUtils.toString(response.getEntity());
		}
	} catch (ClientProtocolException e) {
	
	} catch (IOException e) {
		
	} catch (Exception e) {
		
	}
}

//Post
void Post(String url, Map<String, String> messages) {
	String result = ""; //返回的结果
	HttpPost request = new HttpPost(url);
	List<NameValuePair> params = new ArrayList<NameValuePair>();
	
	for(Map.Entry<String, String> pair: messages.entrySet()) {
		params.add(new BasicNameValuePair(pair.getKey(), pair.getValue()));
	}
	try {
		// 转码
		// TODO 考虑使用自己的转码
		HttpEntity charset = new UrlEncodedFormEntity(params, "utf8");
		request.setEntity(charset);
		
	} catch(Exception e) {
		e.printStackTrace();
	}
	
	try {
		HttpClient client = new DefaultHttpClient();
		HttpResponse response = client.execute(request);
		if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			result = EntityUtils.toString(response.getEntity());
		}
	} catch (ClientProtocolException e) {
	
	} catch (IOException e) {
		
	} catch (Exception e) {
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值