public class HttpPlatform {
String TAG = "HttpPlatform";
private static CookieStore cookieStore = null; // cookie会话
private ParamDown mHttpDownContent = new ParamDown(); // 服务器下行返回参数
public ParamDown HttpPost(ParamUp paramUp) {
int cookieAction = paramUp.cookieAction;
String url = paramUp.type;
String content = paramUp.content;
int contentType = paramUp.contentType;
byte[] binaryData = paramUp.binaryData;
HttpPost httpPost = new HttpPost(url);
DefaultHttpClient httpClient = new DefaultHttpClient();
Log.d(TAG, "-----------------HttpPost");
Log.d(TAG, url);
Log.d(TAG, content);
// 设置服务器当前会话cookie(即get出来的)
if (cookieAction == ParamUp.COOKIE_ACTION_SET) {
httpClient.setCookieStore(cookieStore);
}
switch (contentType) {
case ParamUp.CONTENT_TYPE_JSON: // json 格式
try {
if (content != null) {
// 绑定到请求 Entry
StringEntity stringEntity = new StringEntity(content,
HTTP.UTF_8);
httpPost.setHeader("Content-Type",
"text/plain; charset=utf-8");
System.out.println("----"+stringEntity);
httpPost.setEntity(stringEntity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
break;
case ParamUp.CONTENT_TYPE_BINARY: // 二进制数据
if (paramUp.mHeaderParamsMap != null
&& paramUp.mHeaderParamsMap.size() > 0) {
Set set = paramUp.mHeaderParamsMap.keySet();
for (Object key : set) {
httpPost.addHeader(key.toString(),
paramUp.mHeaderParamsMap.get(key));
}
}
// 图片数据
if (binaryData != null && binaryData.length > 0) {
ByteArrayEntity byteArrayEntity = new ByteArrayEntity(
binaryData);
byteArrayEntity.setContentType("application/octet-stream");
httpPost.setEntity(byteArrayEntity);
}
break;
default:
break;
}
// 发送请求
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
// 读取服务器返回在客户端的cookie
if (cookieAction == ParamUp.COOKIE_ACTION_GET) {
cookieStore = httpClient.getCookieStore();
System.out.println("cookieStore:"+cookieStore.toString());
}
//数据返回
String respondEntityString = EntityUtils.toString(httpResponse.getEntity());
System.out.println("----"+respondEntityString);
mHttpDownContent.result = respondEntityString;
Log.d(TAG, respondEntityString);
return mHttpDownContent;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}