android的HTTP通信,可保持session

1 篇文章 0 订阅
1 篇文章 0 订阅

在android的时候使用JSON做交互的时候,登录以后的信息可以靠该类进行保存。

/**
 * 与服务器通信交互类
 */
package cn.brtx.carsharing.tools;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.brtx.bean.dao.MUser;

import android.util.Log;

public abstract class HTTPtools {
	private final static String TAG = "HttpTools";
	private final static String SERVER_URL = "http://192.168.1.254:8080/Brtx/";//访问地址
	private static CookieStore cookieStore;//定义一个Cookie来保存session
/**
 * 向服务器发送URL请求  获得返回数据
 * @param doUrl stauts的类名
 * @param actionName 方法名
 * @param params 传递的参数
 * @return 获得返回的JSON结果
 */
	public static ActionValue invoke(String doUrl,String actionName, List<NameValuePair> params) {
		Log.e("error connect", "--------------");
		String result = null;
		ActionValue value=null;
		try {
			String url = SERVER_URL + doUrl+".do?action="+actionName;
			Log.d(TAG, "url is" + url);
			HttpPost httpPost = new HttpPost(url);
			if (params != null && params.size() > 0) {
				
				HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
				
				httpPost.setEntity(entity);
			}
			httpPost.addHeader("Content-Type","application/x-www-form-urlencoded; charset=\"UTF-8\"");	
			DefaultHttpClient httpClient = new DefaultHttpClient();
			// 添加Cookie
			if (cookieStore != null) {
				httpClient.setCookieStore(cookieStore);				
			}
			HttpResponse httpResponse = httpClient.execute(httpPost);
			StringBuilder builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					httpResponse.getEntity().getContent()));
			for (String s = reader.readLine(); s != null; s = reader.readLine()) {
				builder.append(s);
			}
			result = builder.toString();
			
			value=GSONTOOLS.getGson().fromJson(result, ActionValue.class);
			
//			MUser user = GSONTOOLS.getGson().fromJson(value.getVALUE(), MUser.class);
			Log.d(TAG, "result is ( " + result + " )");
			// 保存Cookie
			cookieStore = ((AbstractHttpClient) httpClient).getCookieStore();
		} catch (Exception e) {
			Log.e(TAG, e.toString());
		}
		Log.d(TAG, "over");
		return value;
	}

}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值