在android开发中如果我们需要和服务器端交互的时候已经使用apache client项目进行表单的模拟提交。通过返回json对象进而来达到数据的提交与取回,同时又能保证session的有效性以及系统的安全性,这里我封装了一下httpclient的get和post方式来提交数据
- /**
- *
- */
- package com.jiuchongju.util;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- 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.protocol.HTTP;
- import org.apache.http.util.EntityUtils;
- /**
- * Description:
- * @version 1.0
- */
- public class HttpUtil
- {
- // 创建HttpClient对象
- public static HttpClient httpClient ;
- public static final String BASE_URL =
- "http://www.xxx.com/projectname/name_baidu!jsonstring";
- /**
- *
- * @param url 发送请求的URL
- * @return 服务器响应字符串
- * @throws Exception
- */
- public static String getRequest(String url)
- throws Exception
- {
- httpClient= new DefaultHttpClient();
- try{
- // 创建HttpGet对象。
- HttpGet get = new HttpGet(url);
- // 发送GET请求
- HttpResponse httpResponse = httpClient.execute(get);
- // 如果服务器成功地返回响应
- if (httpResponse.getStatusLine()
- .getStatusCode() == 200)
- {
- // 获取服务器响应字符串
- String result = EntityUtils
- .toString(httpResponse.getEntity());
- return result;
- }
- }catch(Exception e){
- e.printStackTrace();
- return "获取数据失败!";
- }finally{
- httpClient.getConnectionManager().shutdown();
- }
- return null;
- }
- /**
- *
- * @param url 发送请求的URL
- * @param params 请求参数
- * @return 服务器响应字符串
- * @throws Exception
- */
- public static String postRequest(String url
- , Map<String ,String> rawParams)
- {
- httpClient= new DefaultHttpClient();
- try{
- // 创建HttpPost对象。
- HttpPost post = new HttpPost(url);
- // 如果传递参数个数比较多的话可以对传递的参数进行封装
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- for(String key : rawParams.keySet())
- {
- //封装请求参数
- params.add(new BasicNameValuePair(key , rawParams.get(key)));
- }
- // 设置请求参数
- post.setEntity(new UrlEncodedFormEntity(
- params,HTTP.UTF_8));
- // 发送POST请求
- HttpResponse httpResponse = httpClient.execute(post);
- // 如果服务器成功地返回响应
- if (httpResponse.getStatusLine()
- .getStatusCode() == 200)
- {
- // 获取服务器响应字符串
- String result = EntityUtils
- .toString(httpResponse.getEntity());
- return result;
- }
- }catch(Exception e){
- e.printStackTrace();
- }finally{
- httpClient.getConnectionManager().shutdown();
- }
- return null;
- }
- }
需要说明的是,这个一般不能直接在主线程来做这个动作,这样会因为网络问题造成主线程假死。手机客户端的UI卡掉
一般我都是异步进行数据的调用