http请求模拟
2016-05-24 16:50
525 查看
一、HttpClient
/**
* 对字符串进行MD5加密
*
* @param text
* 明文
*
* @return 密文
*/
public static String md5(String text) {
MessageDigest msgDigest = null;
try {
msgDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(
"System doesn't support MD5 algorithm.");
}
msgDigest.update(text.getBytes());
byte[] bytes = msgDigest.digest();
byte tb;
char low;
char high;
char tmpChar;
String md5Str = new String();
for (int i = 0; i < bytes.length; i++) {
tb = bytes[i];
tmpChar = (char) ((tb >>> 4) & 0x000f);
if (tmpChar >= 10) {
high = (char) (('a' + tmpChar) - 10);
} else {
high = (char) ('0' + tmpChar);
}
md5Str += high;
tmpChar = (char) (tb & 0x000f);
if (tmpChar >= 10) {
low = (char) (('a' + tmpChar) - 10);
} else {
low = (char) ('0' + tmpChar);
}
md5Str += low;
}
return md5Str;
}
public static void printJson(String jsonStr){
System.out.println(formatJson(jsonStr));
}
/**
* 格式化
* @param jsonStr
* @return
*/
public static String formatJson(String jsonStr) {
if (null == jsonStr || "".equals(jsonStr)) return "";
StringBuilder sb = new StringBuilder();
char last = '\0';
char current = '\0';
int indent = 0;
for (int i = 0; i < jsonStr.length(); i++) {
last = current;
current = jsonStr.charAt(i);
switch (current) {
case '{':
case '[':
sb.append(current);
sb.append('\n');
indent++;
addIndentBlank(sb, indent);
break;
case '}':
case ']':
sb.append('\n');
indent--;
addIndentBlank(sb, indent);
sb.append(current);
break;
case ',':
sb.append(current);
if (last != '\\') {
sb.append('\n');
addIndentBlank(sb, indent);
}
break;
default:
sb.append(current);
}
}
return sb.toString();
}
/**
* 添加space
* @param sb
* @param indent
*/
private static void addIndentBlank(StringBuilder sb, int indent) {
for (int i = 0; i < indent; i++) {
sb.append('\t');
}
}
}
二、HttpAsyncClient
@Override
public Map<String, Object> updateStoreProduct(String product) {
List<Param> param = Arrays.asList(new Param("product", product));
return this.post("storeproductapi.do", "updateStoreProduct", param);
}
Map<String, Object> post(String url, String method, List<Param> param) {
List<Param> params = param;
if (params == null) {
params = new ArrayList<>();
} else {
params = new ArrayList<>(param);
}
params.add(new Param("method", method));
params.add(new Param("charset", "gbk"));
//设置请求的来源,W:触屏版,A:android App,I:ios App
params.add(new Param("source", "W"));
logger.debug("param:" + JsonUtil.writeValue(params));
try {
Map<String, Object> ret = HttpClientUtil.post(this.base + "api/"
+ url, params, "gbk");
logger.debug("ret:" + JsonUtil.writeValue(ret));
return ret;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param url
* @param params
* @param charset
* @return
* @throws IOException
* @throws ExecutionException Http
* @throws InterruptedException
*/
public static Map<String,Object> post(String url,List<Param> params,String charset) throws IOException, InterruptedException, ExecutionException{
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
try{
httpclient.start();
HttpPost post=new HttpPost(url);
List<NameValuePair> form=new ArrayList<>();
for(Param p:params){
form.add(new BasicNameValuePair(p.getName(), p.getValue()));
}
post.setEntity(new UrlEncodedFormEntity(form, charset));
HttpResponse resp=httpclient.execute(post, null).get();
return JsonUtil.readValue(IOUtils.toString(resp.getEntity().getContent(), charset),Map.class);
}finally{
httpclient.close();
}
}
三、UrlConnection
四、volley
五、okhttp、retrofit
后两种是android通用通信框架
import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.http.client.utils.URIUtils; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public class TestHttp { private static String ENCODED_TYPE = "GBK"; private static String scheme = "http"; //本机 // private static String host = "192.168.7.19"; // private static int port = 8088; // private static String path = "/bocep2c/api/storeorderapi.do"; //测试服务器 private static String host = "111.160.xxx.xxx"; private static int port = 24080; private static String path = "/api/storeorderapi.do"; private static String methodValue = "getOrderDetail"; /** * @param args */ public static void main(String[] args) { HttpClient httpClient = new HttpClient(); String response = httpRequest("null", httpClient); printJson(response); } private static String httpRequest(String data, HttpClient httpClient) { // System.out.println("the order is:"+data); //httpURL = Utf8URLencode(httpURL); List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair("method", methodValue)); params.add(new BasicNameValuePair("charset", ENCODED_TYPE)); params.add(new BasicNameValuePair("productId", "c9gb2147")); params.add(new BasicNameValuePair("productIds", "usuu2433,fhks2432")); params.add(new BasicNameValuePair("userId", "1111110145")); params.add(new BasicNameValuePair("token", md5("1111110145"))); //params.add(new BasicNameValuePair("name", "honghailiang666")); params.add(new BasicNameValuePair("promotionType", "K")); params.add(new BasicNameValuePair("pageIndex", "1")); params.add(new BasicNameValuePair("pageSize", "10")); params.add(new BasicNameValuePair("type", "0")); params.add(new BasicNameValuePair("bestUserId", "100005368")); params.add(new BasicNameValuePair("password", md5("1111110145"+"bocetest123"))); params.add(new BasicNameValuePair("idCard", "100005369111111")); params.add(new BasicNameValuePair("province", "100120000000000")); params.add(new BasicNameValuePair("orderId", "15121000533500")); params.add(new BasicNameValuePair("storeId", "1111110145")); params.add(new BasicNameValuePair("storeIds", "1111110829")); params.add(new BasicNameValuePair("giftCardId", "402886594eb4b907014eb87ec0a10023")); params.add(new BasicNameValuePair("storeViewId", "f77ea0dc49ebb8a20149f95c8921015e")); params.add(new BasicNameValuePair("viewCount", "8")); params.add(new BasicNameValuePair("pageType", "1")); params.add(new BasicNameValuePair("searchKey", "")); params.add(new BasicNameValuePair("reason", "触屏版测试")); params.add(new BasicNameValuePair("logisticsId", "f77ea0dc49314a44014931d68504005e")); params.add(new BasicNameValuePair("expressNo", "15112000513900")); params.add(new BasicNameValuePair("fhNote", "触屏版测试")); params.add(new BasicNameValuePair("rewardStatus", "0")); params.add(new BasicNameValuePair("categoryId", "tkox1665")); params.add(new BasicNameValuePair("friendId", "1211111112")); params.add(new BasicNameValuePair("note", "触屏版")); params.add(new BasicNameValuePair("loginType", "3")); params.add(new BasicNameValuePair("note", "触屏版")); //加购物车的商品信息 JSONObject jsonObject = new JSONObject(); jsonObject.put("productId", "24qm2538"); jsonObject.put("quantity", 500); jsonObject.put("listPrice", 20); jsonObject.put("status", false); jsonObject.put("unitPrice", 10); params.add(new BasicNameValuePair("product", jsonObject.toString())); //删除购物车商品 JSONObject jsonObject2 = new JSONObject(); jsonObject2.put("productId", "sxkt2277"); jsonObject2.put("id", "1449626295719"); jsonObject2.put("number", 1); JSONArray ja = new JSONArray(); ja.add(jsonObject2); params.add(new BasicNameValuePair("products", ja.toString())); //编码,会对(非ascii码)非法字符进行%号编码 String param = URLEncodedUtils.format(params, ENCODED_TYPE); //String param = "userId=洪海亮"; URI uri = null; try { uri = URIUtils.createURI(scheme, host, port, path, param, null); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Map<String, String> paramMap = new HashMap<String, String>(); // paramMap.put("method", methodValue); // paramMap.put("charset", ENCODED_TYPE); // paramMap.put("productId", "c9gb2147"); // // String encodeZ = null; // try { // encodeZ = URLEncoder.encode("洪海亮", "GBK"); // } catch (UnsupportedEncodingException e2) { // // TODO Auto-generated catch block // e2.printStackTrace(); // } // paramMap.put("userId", encodeZ); // paramMap.put("pageIndex", "1"); // paramMap.put("pageSize", "10"); // Set<String> keySet = paramMap.keySet(); // StringBuffer requestParams = new StringBuffer(); // for (String key : keySet) { // String encodeParam = key + "=" + paramMap.get(key); // requestParams.append(encodeParam + "&"); // } // // String paramS = requestParams.toString(); // // new URL 会对其中的非法字符进行编码%号编码(但是中文要先进行GBK或者UTF-8编码),% %25 // // /** // *Url编码默认使用的字符集是US-ASCII // *对于非ASCII字符,需要使用ASCII字符集的超集进行编码得到相应的字节,然后对每个字节执行百分号编码。 // * // * // */ // // URI uri = null; // try { // uri = new URI(scheme, null, host, port, path, paramS, null); // } catch (URISyntaxException e1) { // // TODO Auto-generated catch block // e1.printStackTrace(); // // } String respones = null; if(uri != null && uri.toString()!= null && uri.toString()!= "") { PostMethod postMethod = new PostMethod(uri.toString()); postMethod.addRequestHeader("Content-Type", "text/html;charset=GBK"); postMethod.setRequestBody(data); // 执行postMethod try { int statusCode = httpClient.executeMethod(postMethod); // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发 // 301或者302 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { // 从头中取出转向的地址 Header locationHeader = postMethod .getResponseHeader("location"); String location = null; if (locationHeader != null) { location = locationHeader.getValue(); System.out.println("The page was redirected to:" + location); } else { System.err.println("Location field value is null."); } } String encode = postMethod.getResponseCharSet(); respones = postMethod.getResponseBodyAsString(); // System.out.println("the resule is:" + respones); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { // 发生网络异常 e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } return respones; }
/**
* 对字符串进行MD5加密
*
* @param text
* 明文
*
* @return 密文
*/
public static String md5(String text) {
MessageDigest msgDigest = null;
try {
msgDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(
"System doesn't support MD5 algorithm.");
}
msgDigest.update(text.getBytes());
byte[] bytes = msgDigest.digest();
byte tb;
char low;
char high;
char tmpChar;
String md5Str = new String();
for (int i = 0; i < bytes.length; i++) {
tb = bytes[i];
tmpChar = (char) ((tb >>> 4) & 0x000f);
if (tmpChar >= 10) {
high = (char) (('a' + tmpChar) - 10);
} else {
high = (char) ('0' + tmpChar);
}
md5Str += high;
tmpChar = (char) (tb & 0x000f);
if (tmpChar >= 10) {
low = (char) (('a' + tmpChar) - 10);
} else {
low = (char) ('0' + tmpChar);
}
md5Str += low;
}
return md5Str;
}
public static void printJson(String jsonStr){
System.out.println(formatJson(jsonStr));
}
/**
* 格式化
* @param jsonStr
* @return
*/
public static String formatJson(String jsonStr) {
if (null == jsonStr || "".equals(jsonStr)) return "";
StringBuilder sb = new StringBuilder();
char last = '\0';
char current = '\0';
int indent = 0;
for (int i = 0; i < jsonStr.length(); i++) {
last = current;
current = jsonStr.charAt(i);
switch (current) {
case '{':
case '[':
sb.append(current);
sb.append('\n');
indent++;
addIndentBlank(sb, indent);
break;
case '}':
case ']':
sb.append('\n');
indent--;
addIndentBlank(sb, indent);
sb.append(current);
break;
case ',':
sb.append(current);
if (last != '\\') {
sb.append('\n');
addIndentBlank(sb, indent);
}
break;
default:
sb.append(current);
}
}
return sb.toString();
}
/**
* 添加space
* @param sb
* @param indent
*/
private static void addIndentBlank(StringBuilder sb, int indent) {
for (int i = 0; i < indent; i++) {
sb.append('\t');
}
}
}
二、HttpAsyncClient
@Override
public Map<String, Object> updateStoreProduct(String product) {
List<Param> param = Arrays.asList(new Param("product", product));
return this.post("storeproductapi.do", "updateStoreProduct", param);
}
Map<String, Object> post(String url, String method, List<Param> param) {
List<Param> params = param;
if (params == null) {
params = new ArrayList<>();
} else {
params = new ArrayList<>(param);
}
params.add(new Param("method", method));
params.add(new Param("charset", "gbk"));
//设置请求的来源,W:触屏版,A:android App,I:ios App
params.add(new Param("source", "W"));
logger.debug("param:" + JsonUtil.writeValue(params));
try {
Map<String, Object> ret = HttpClientUtil.post(this.base + "api/"
+ url, params, "gbk");
logger.debug("ret:" + JsonUtil.writeValue(ret));
return ret;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param url
* @param params
* @param charset
* @return
* @throws IOException
* @throws ExecutionException Http
* @throws InterruptedException
*/
public static Map<String,Object> post(String url,List<Param> params,String charset) throws IOException, InterruptedException, ExecutionException{
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
try{
httpclient.start();
HttpPost post=new HttpPost(url);
List<NameValuePair> form=new ArrayList<>();
for(Param p:params){
form.add(new BasicNameValuePair(p.getName(), p.getValue()));
}
post.setEntity(new UrlEncodedFormEntity(form, charset));
HttpResponse resp=httpclient.execute(post, null).get();
return JsonUtil.readValue(IOUtils.toString(resp.getEntity().getContent(), charset),Map.class);
}finally{
httpclient.close();
}
}
三、UrlConnection
四、volley
五、okhttp、retrofit
后两种是android通用通信框架
相关文章推荐
- 深入剖析Android的Volley库中的图片加载功能
- Android的HTTP类库Volley入门学习教程
- Android开发中使用Volley库发送HTTP请求的实例教程
- Android的HTTP操作库Volley的基本使用教程
- Android Volley框架使用源码分享
- 深入解读Android的Volley库的功能结构
- Android Retrofit 2.0框架上传图片解决方案
- Netroid:强大、快速、易用、可扩展基于Volley实现的Android Http库
- Android Volley运用
- 跟我一起看Retrofit 2.0的源码
- OkHttp的Interceptor原理分析
- Android Volley完全解析(一),初识Volley的基本用法
- Android Volley完全解析(二),使用Volley加载网络图片
- Android Volley完全解析(三),定制自己的Request
- Android Volley完全解析(四),带你从源码的角度理解Volley
- android listview 异步加载图片并防止错位
- Android 网络通信框架Volley简介
- Retrofit官方简介
- Volley的unit test
- http缓存