工作中的httpclient 实例,使你较快熟悉httpclient使用流程。
1 httpclient测试类
import
java.util.ArrayList;
import
java.util.Date;
import
java.util.List;
import
net.sf.json.JSONObject;
import
org.apache.http.HttpEntity;
import
org.apache.http.HttpResponse;
import
org.apache.http.NameValuePair;
import
org.apache.http.client.entity.UrlEncodedFormEntity;
import
org.apache.http.client.methods.HttpPost;
import
org.apache.http.impl.client. DefaultHttpClient;
import
org.apache.http.message.BasicNameValuePair;
import
org.apache.http.util.EntityUtils;
import
org.junit.Test;
import
com.xx.AESAPPUtils;
import
com.xx.GzipAESUtil;
public
class
HttpClientTest {
@Test
public
void
http() {
String pre =
"appUser/appCheckVersion"
; //请求的Controller和对应的方法
String url =
"http://localhost:8080/ass/"
+ pre; // 请求url地址
JSONObject jo =
new
JSONObject();
jo.put(
"sjId"
,
""
+
new
Date().getTime());
jo.put(
"jkId"
,
"mtms001"
);
jo.put(
"mkId"
,
"1002"
);
jo.put(
"userId"
,
"0004019153"
);
jo.put(
"baiduId"
,
"4dasxc"
);
jo.put(
"appType"
,
"ios"
);
jo.put(
"appVersion"
,
"1.0.1"
);
System.
out
.println(jo.toString()); // 将请求参数封装成json格式
try
{
HttpPost httppost =
new
HttpPost(url);
List<NameValuePair> params =
new
ArrayList<NameValuePair>();
params.add(
new
BasicNameValuePair(
"ass"
, AESAPPUtils.encryptAES(jo
.toString()))); // 传递给后台的参数只有一个,名为ass,参数值由AESAPPUtils.encryptAES方法加密生成。提高安全性。
httppost.setEntity(
new
UrlEncodedFormEntity(params,
"UTF-8"
));
HttpResponse httpResponse =
new
DefaultHttpClient()
.execute(httppost); // 发起请求
HttpEntity entity2 = httpResponse.getEntity(); // 得到回复
String result = EntityUtils. toString(entity2);
System.
out
.println(GzipAESUtil. decryptAESThenUnCompress(result));
}
catch
(Exception e) {
e.printStackTrace();
}
}
}
2 后台的controller
import
java.util.Map;
import
javax.annotation.Resource;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
import
net.sf.json.JSONObject;
import
org.slf4j.Logger;
import
org.slf4j.LoggerFactory;
import
org.springframework.stereotype.Controller;
import
org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.ResponseBody;
import
com.xx.APPErrorInfo;
import
com.
xx
.AppUserService;
import
com.
xx
.GzipAESUtil;
import
com.
xx
.ReciveMessageConvert;
@Controller
@RequestMapping
(
"/appUser"
)
public
class
AppUserController {
@Resource
private
AppUserService
appUserService
;
private
static
final
Logger
log
= LoggerFactory.getLogger(AppUserController.
class
);
@RequestMapping
(value=
"/appCheckVersion "
, produces=
"text/plain;charset=UTF-8"
)
public
@ResponseBody
String appCheckVersion (HttpServletRequest request, HttpServletResponse response){
Map<String, Object> appParam =
null
;
JSONObject result =
new
JSONObject();
try
{
appParam = ReciveMessageConvert.requestToMap(request);
result =
appUserService
.appCheckVersion(appParam);
}
catch
(Exception e) {
log
.error(e.getMessage(),e);
result.put(APPErrorInfo.
ERRORCODE
, APPErrorInfo.
E10000
);
result.put(APPErrorInfo.
ERRORMSG
, APPErrorInfo.
M10000
);
}
log
.info(
"reply message :\t"
+result.toString());
return
GzipAESUtil.compressThenEncryptAES(result.toString());
}
}
3
ReciveMessageConvert
类
import
java.util.Map;
import
javax.servlet.http.HttpServletRequest;
import
org.slf4j.Logger;
import
org.slf4j.LoggerFactory;
public
class
ReciveMessageConvert {
private
static
Logger
log
= LoggerFactory.getLogger(ReciveMessageConvert.
class
);
private
static
final
String
APP_MESSAGE_KEY
=
"ass"
;
@SuppressWarnings
(
"unchecked"
)
public
static
Map<String, Object> requestToMap(HttpServletRequest request)
throws
Exception{
String parameter = request.getParameter(
APP_MESSAGE_KEY
);
String recive = AESAPPUtils. decryptAES(parameter);
Map<String, Object> map = JsonUtil.jsonStringToMap(recive);
log
.info(
"recive message:\t"
+recive);
return
map;
}
}
4 加密解密工具类
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AESAPPUtils {
public static byte[] key = new byte[] { 0x08, 0x08, 0x04, 0x0b, 0x02, 0x0f, 0x0b, 0x0c,0x01, 0x03, 0x09, 0x07, 0x0c, 0x03, 0x07, 0x0a };
/*
* 转为十六进制
*/
private static String asHex(byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
/*
* 转为二进制
*/
private static byte[] asBin(String src) {
if (src.length() < 1)
return null;
byte[] encrypted = new byte[src.length() / 2];
for (int i = 0; i < src.length() / 2; i++) {
int high = Integer.parseInt(src.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(src.substring(i * 2 + 1, i * 2 + 2), 16);
encrypted[i] = (byte) (high * 16 + low);
}
return encrypted;
}
/*
* 加密
*/
public static String encryptAES(String data) {
SecretKeySpec sKey = new SecretKeySpec(key, "AES");
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sKey);
byte[] encrypted = cipher.doFinal(data.getBytes());
return asHex(encrypted);
} catch (Exception e) {
return null;
}
}
/*
* 解密
*/
public static String decryptAES(String encData) {
byte[] tmp = asBin(encData);
SecretKeySpec sKey = new SecretKeySpec(key, "AES");
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sKey);
byte[] decrypted = cipher.doFinal(tmp);
return new String(decrypted);
} catch (Exception e) {
return null;
}
}
}
5
JsonUtil
类
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONBuilder;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ClassPathResource;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
@SuppressWarnings("all")
public final class JsonUtil {
private static Logger log = Logger.getLogger(JsonUtil.class);
/**
* 获取到Map值;
*
* @param jsonString
* @return
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
public static Map jsonStringToMap(String jsonString) throws Exception {
Map hashMap = new HashMap();
if (null == jsonString) {
return null;
}
try {
hashMap = (Map) getJsonStringToObject(jsonString, HashMap.class);
} catch (Exception e) {
e.printStackTrace();
}
return hashMap;
}
/**
* JsonString 转换成对应Object
*
* @return
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
public static Object getJsonStringToObject(String jsonString, Class cls) throws Exception {
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
return mapper.readValue(jsonString, cls);
}
}
6
压缩加密解密压缩工具类
/**
* 压缩加密 解密压缩
*/
public
class
GzipAESUtil {
/**
* 先压缩后加密
*
@param
str 要处理的字符串
*
@return
*/
public
static
String compressThenEncryptAES(String str){
try
{
return
AESAPPUtils.encryptAES(GZipStrUtil.compress(str));
}
catch
(Exception e) {
e.printStackTrace();
return
null
;
}
}
/**
* 先解密后解压缩
*
@param
str 要处理的字符串
*
@return
*/
public
static
String decryptAESThenUnCompress(String str){
try
{
return
GZipStrUtil.unCompress(AESAPPUtils.decryptAES(str));
}
catch
(Exception e) {
e.printStackTrace();
return
null
;
}
}
}