手机端与服务端交互类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lyh1234/article/details/45311201
Android中通过HTTP协议与服务器进行数据交换
package com.suniot.caigou.utils;

import java.io.File;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.text.TextUtils;

import com.lyh.lib.utils.DebugLog;
import com.suniot.caigou.config.Constants;
import com.suniot.caigou.config.Shared;
import com.suniot.caigou.entity.JsonResult;
import com.suniot.caigou.parser.JsonParser;
import com.suniot.caigou.request.base.RequestParameter;

/**
 * @author lyh
 * @description 手机端与服务端交互类
 * @date 2015-04-03
 */
public class ServerUtils<T> {

	private RequestParameter rp;
	private Class<T> classOfT;
	private Type typeOfT;
	private String ECS_ID = "ECS_ID";

	public ServerUtils(RequestParameter rp, Class<T> classOfT) {
		this.rp = rp;
		this.classOfT = classOfT;
		init();
	}

	public ServerUtils(RequestParameter rp, Type typeOfT) {
		this.rp = rp;
		this.typeOfT = typeOfT;
		init();
	}

	public DefaultHttpClient client;

	/**
	 * 以HttpPost请求服务,并返回需要的格式化信息
	 */
	public JsonResult<T> post() {
		String url = rp.getUrl().concat(UrlUtils.createLinkString(rp.getHttpGetParams()));
		DebugLog.e(url);
		HttpPost post = new HttpPost(url);
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, Constants.CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, Constants.SO_TIMEOUT);
		post.setParams(params);
		post.setHeaders(Constants.headers);
		post.setHeader("Cookie", getCookie());
		JsonResult<T> result = null;

		try {
			MultipartEntityBuilder meb = MultipartEntityBuilder.create();

			// 添加数据
			if (rp.getHttpPostParams() != null
					&& rp.getHttpPostParams().size() > 0) {
				for (Map.Entry<String, Object> entry : rp.getHttpPostParams().entrySet()) {
					if (entry.getValue() != null) {
						ContentType type = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), Constants.DEFAULT_CHARSET);
						meb.addTextBody(entry.getKey(), String.valueOf(entry.getValue()), type);
					}
				}
			}

			// 添加文件
			if (rp.getHttpPostFiles() != null
					&& rp.getHttpPostFiles().size() > 0) {
				for (Map.Entry<String, String> entry : rp.getHttpPostFiles().entrySet()) {
					File file = new File(entry.getValue());
					if (file.exists()) {
						meb.addBinaryBody(entry.getKey(), file);
					}
				}
			}

			// 生成 HTTP 实体
			HttpEntity reqEntity = meb.build();
			post.setEntity(reqEntity);

			// 执行 HTTP 请求
			HttpResponse response = client.execute(post);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String json = EntityUtils.toString(response.getEntity(), Constants.DEFAULT_CHARSET);
				DebugLog.e(json);
				if (classOfT != null)
					result = new JsonParser<T>(classOfT).parseJSON(json);
				else if (typeOfT != null)
					result = new JsonParser<T>(typeOfT).parseJSON(json);
			}
		} catch (Exception e) {
			DebugLog.e(e.toString());
		}

		saveCookie();
		return result;
	}

	/**
	 * 以HttpGet请求服务,并返回需要的格式化信息
	 */
	public JsonResult<T> get() {
		String url = rp.getUrl().concat(UrlUtils.createLinkString(rp.getHttpGetParams()));
		DebugLog.e(url);
		HttpGet get = new HttpGet(url);
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, Constants.CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, Constants.SO_TIMEOUT);
		get.setParams(params);
		get.setHeaders(Constants.headers);
		get.setHeader("Cookie", getCookie());
		JsonResult<T> result = null;

		try {
			HttpResponse response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String json = EntityUtils.toString(response.getEntity(), Constants.DEFAULT_CHARSET);
				DebugLog.e(json);
				if (classOfT != null)
					result = new JsonParser<T>(classOfT).parseJSON(json);
				else if (typeOfT != null)
					result = new JsonParser<T>(typeOfT).parseJSON(json);
			}
		} catch (Exception e) {
			DebugLog.e(e.toString());
		}
		saveCookie();
		return result;
	}

	/**
	 * 保存当前Cookie
	 */
	public void saveCookie() {
		if (client != null)
			CookieUtils.saveCookie(rp.getContext(), client);
	}

	/**
	 * 获得需要发送至服务器的Cookie
	 * 
	 * @return
	 */
	private String getCookie() {
		String cookie = Shared.getCookie(rp.getContext());
		String sid = Shared.getSid(rp.getContext());
		if (!cookie.contains(ECS_ID) && !TextUtils.isEmpty(sid)) {
			cookie += String.format("%s=%s;", ECS_ID, sid);
		}
		return cookie;
	}

	/**
	 * 初始化
	 */
	private void init() {
		client = new DefaultHttpClient();
		if (rp.getHttpGetParams() == null)
			rp.setHttpGetParams(new HashMap<String, Object>());
		if (rp.getHttpPostParams() == null)
			rp.setHttpPostParams(new HashMap<String, Object>());
		rp.getHttpGetParams().put(Constants.SOURCE_NAME, Constants.SOURCE_VALUE);
		rp.getHttpPostParams().put(Constants.SOURCE_NAME, Constants.SOURCE_VALUE);
		rp.getHttpGetParams().put(Constants.OUTPUT_NAME, Constants.OUTPUT_VALUE);
	}
}

猜你喜欢

转载自blog.csdn.net/lyh1234/article/details/45311201