Java模拟Http访问将返回的JSON解析为Bean对象
应用场景:某系统访问另一个系统获取一些数据,其中这些返回数据类型必须是JSON格式,接受系统可以将结果转换为简单的Bean对象,也可以将返回的是集合数据转换成List。这就需要我们模拟一个Http访问,然后处理返回的JSON数据。
方案选型:看了看网上的很多Demo,都是比较老的。其中应用的apache的框架现在也已经找不到了。所以决定亲自去apache官网去看看。发现以前的httpclient包已经独立出来命名为Apache HttpComponents。当前最新包为4.3.3。我采用的是OSChina的Maven源,还不错,已经有资源了。而JSON解析才用了最为流行的Jackson。
Demo示例:
Test.java 返回的JSON数据将要被解析成为的对象类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package org.uugu.common.http; public class Test { private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } |
HttpUtil.java Http访问工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
package org.uugu.common.http; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.JavaType; /** * Http访问工具类 * @author Silence * */ public class HttpUtil { public static void main(String[] args) throws Exception { Map<String, String> params = new HashMap<>(); params.put("userName","abc"); params.put("password","123"); Test test = doGet("http://www.uugu.org/abc.do", params, Test.class); Test test2 = doPost("http://www.uugu.org/abc.do", params, Test.class); System.out.println(test.getUserName()); System.out.println(test2.getPassword()); } /** * Get访问方式 * @param url 访问地址 * @param params 请求参数 * @param clazz 返回数据背解析成为的对象类型 * @param argClasses 返回集合类型时的泛型类型 * @return * @throws Exception */ public static <T> T doGet(String url, Map<String, String> params, Class<T> clazz, Class<?>... argClasses) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); ObjectMapper objectMapper = new ObjectMapper(); String responseBody = ""; try { RequestBuilder requestBuilder = RequestBuilder.get().setUri( new URI(url)); if (params != null) { for (Entry<String, String> entry : params.entrySet()) { requestBuilder.addParameter(entry.getKey(), entry.getValue()); } } HttpUriRequest httpGet = requestBuilder.build(); httpGet.addHeader("Content-Type", "text/html;charset=UTF-8"); CloseableHttpResponse response = httpclient.execute(httpGet); try { HttpEntity entity = response.getEntity(); // 判断执行结果返回状态 int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { responseBody = entity != null ? EntityUtils .toString(entity) : null; } else { throw new ClientProtocolException( "Unexpected response status: " + status); } // 判断返回类型是否为JSON ContentType contentType = ContentType.getOrDefault(entity); if (!contentType.getMimeType().equals( ContentType.APPLICATION_JSON.getMimeType())) { throw new ClientProtocolException( "Unexpected content type: " + contentType); } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } if (argClasses.length > 0) { JavaType javaType = objectMapper.getTypeFactory() .constructParametricType(clazz, argClasses); return objectMapper.readValue(responseBody, javaType); } else { return objectMapper.readValue(responseBody, clazz); } } /** * Post访问方式 * @param url 访问地址 * @param params 请求参数 * @param clazz 返回数据背解析成为的对象类型 * @param argClasses 返回集合类型时的泛型类型 * @return * @throws Exception */ public static <T> T doPost(String url, Map<String, String> params, Class<T> clazz, Class<?>... argClasses) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); ObjectMapper objectMapper = new ObjectMapper(); String responseBody = ""; HttpPost httpPost = new HttpPost(); //httpPost.addHeader("Content-Type", "text/html;charset=UTF-8"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if (params != null) { for (Entry<String, String> entry : params.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry .getValue())); } } httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response = httpclient.execute(httpPost); try { HttpEntity entity = response.getEntity(); // 判断执行结果返回状态 int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { responseBody = entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException( "Unexpected response status: " + status); } // 判断返回类型是否为JSON ContentType contentType = ContentType.getOrDefault(entity); if (!contentType.getMimeType().equals( ContentType.APPLICATION_JSON.getMimeType())) { throw new ClientProtocolException("Unexpected content type: " + contentType); } EntityUtils.consume(entity); } finally { response.close(); httpclient.close(); } if (argClasses.length > 0) { JavaType javaType = objectMapper.getTypeFactory() .constructParametricType(clazz, argClasses); return objectMapper.readValue(responseBody, javaType); } else { return objectMapper.readValue(responseBody, clazz); } } } |
需求简单,实现也没什么难度,仅为工作总结。