用到的类:
包: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) {
}
}