首页 > 代码库 > java发送http的get、post请求
java发送http的get、post请求
package com.opentrans.otms.kaka.wx.utils; import java.io.File; import java.net.URI; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.lcc.handler.CommonResponseHandler; import com.lcc.handler.IResponseHandler; 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.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.config.ConnectionConfig; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.CollectionUtils; import com.lcc.dto.ActionResult; public class HttpUtils { private static Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class); public static CloseableHttpClient buildHttpClient() { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().useSystemProperties(); httpClientBuilder.setDefaultConnectionConfig( ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build()); CloseableHttpClient httpClient = httpClientBuilder.build(); return httpClient; } public static ActionResult get(String url) { return get(url, null, null); } public static ActionResult get(String url, Map<String, String> headers) { return get(url, null, headers); } public static ActionResult get(String url, List<NameValuePair> params, Map<String, String> headers) { ActionResult result = new ActionResult(); CloseableHttpClient httpClient = buildHttpClient(); HttpGet request = null; try { request = new HttpGet(url); if (!CollectionUtils.isEmpty(params)) { String str = EntityUtils.toString(new UrlEncodedFormEntity(params)); request.setURI(new URI(url + "?" + str)); } if (headers != null) { for (Entry<String, String> entry : headers.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } LOGGER.info("Send request: " + request.getURI()); HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity, "UTF-8"); if (entity != null) { EntityUtils.consume(entity); } int code = response.getStatusLine().getStatusCode(); solveResponse(code, body, result, null); } catch (Exception e) { result.setStatus(ActionResult.FAIL); result.setMessage(e.getMessage()); LOGGER.error("Failed to receive response:", e); } finally { closeHttpClient(httpClient); } return result; } public static ActionResult post(String url, String content, String contentType) { return post(url, content, null, contentType); } public static ActionResult post(String url, String content, Map<String, String> headers, String contentType) { return post(url, content, headers, contentType, null); } public static ActionResult post(String url, String content, Map<String, String> headers, String contentType, IResponseHandler responseHandler) { ActionResult result = new ActionResult(); CloseableHttpClient httpClient = buildHttpClient(); HttpPost request = null; try { request = new HttpPost(url); StringEntity payload = new StringEntity(content, "UTF-8"); payload.setContentType(contentType); payload.setContentEncoding("UTF-8"); request.setEntity(payload); if (headers != null) { for (Entry<String, String> entry : headers.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } LOGGER.info("Send request: " + request.getURI()); LOGGER.info("The payload: " + content); HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity, "UTF-8"); if (entity != null) { EntityUtils.consume(entity); } int code = response.getStatusLine().getStatusCode(); solveResponse(code, body, result, responseHandler); } catch (Exception e) { result.setStatus(ActionResult.FAIL); result.setMessage(e.getMessage()); LOGGER.error("Failed to receive response:", e); } finally { closeHttpClient(httpClient); } return result; } public static ActionResult postFile(String url, Map<String, File> files, Map<String, String> headers, String contentType) { ActionResult result = new ActionResult(); CloseableHttpClient httpClient = buildHttpClient(); HttpPost request = null; try { request = new HttpPost(url); if (headers != null) { for (Entry<String, String> entry : headers.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); String fileName = ""; for (Entry<String, File> entry : files.entrySet()) { fileName = entry.getKey(); FileBody file = new FileBody(entry.getValue()); entityBuilder.addPart(entry.getKey(), file); } request.setEntity(entityBuilder.build()); request.setHeader("Content-Disposition", "attachment;filename=" + fileName); LOGGER.info("Send request: " + request.getURI()); HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity); if (entity != null) { EntityUtils.consume(entity); } int code = response.getStatusLine().getStatusCode(); solveResponse(code, body, result, null); } catch (Exception e) { result.setStatus(ActionResult.FAIL); result.setMessage(e.getMessage()); LOGGER.error("Failed to receive response:", e); } finally { closeHttpClient(httpClient); } return result; } public static ActionResult put(String url, String content, String contentType) { return put(url, content, null, contentType); } public static ActionResult put(String url, String content, Map<String, String> headers, String contentType) { ActionResult result = new ActionResult(); CloseableHttpClient httpClient = buildHttpClient(); HttpPut request = null; try { request = new HttpPut(url); StringEntity payload = new StringEntity(content, "UTF-8"); payload.setContentType(contentType); payload.setContentEncoding("UTF-8"); request.setEntity(payload); if (headers != null) { for (Entry<String, String> entry : headers.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } LOGGER.info("Send request: " + request.getURI()); LOGGER.info("The payload: " + content); HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity, "UTF-8"); if (entity != null) { EntityUtils.consume(entity); } int code = response.getStatusLine().getStatusCode(); solveResponse(code, body, result, null); } catch (Exception e) { result.setStatus(ActionResult.FAIL); result.setMessage(e.getMessage()); LOGGER.error("Failed to receive response:", e); } finally { closeHttpClient(httpClient); } return result; } private static void solveResponse(int code, String body, ActionResult result, IResponseHandler responseHandler) { LOGGER.info("Received response, the code is " + code + ", the content is" + body); if (responseHandler == null) { responseHandler = new CommonResponseHandler(); } responseHandler.processResponse(code, body, result); } private static void closeHttpClient(CloseableHttpClient httpClient) { try { if (httpClient != null) { httpClient.close(); } } catch (Exception e) { LOGGER.error("httpclient close exception", e); } } }
上面utils里面用到的IResponseHandler接口
package com.lcc.handler; import com.lcc.dto.ActionResult; public interface IResponseHandler { void processResponse(int code, String body, ActionResult result); }
实现类CommonResponseHandler
package com.lcc.handler; import com.lcc.dto.ActionResult; import org.apache.http.HttpStatus; public class CommonResponseHandler implements IResponseHandler { @Override public void processResponse(int code, String body, ActionResult result) { if (code == HttpStatus.SC_OK) { result.setData(body); } else if (code == 421) { result.setStatus(ActionResult.UNAUTH); result.setMessage("${service.unauth}"); } else if (code == 531) { result.setStatus(ActionResult.INVALID_ACTIVATION_CODE); result.setMessage("${service.invalid.token}"); } else if (code == HttpStatus.SC_INTERNAL_SERVER_ERROR) { result.setStatus(ActionResult.FAIL); result.setMessage("${service.internal.error}"); } else if (code == HttpStatus.SC_SERVICE_UNAVAILABLE) { result.setStatus(ActionResult.FAIL); result.setMessage("${service.unavailable}"); } else { result.setStatus(ActionResult.FAIL); result.setMessage(body); } } }
ActionResult类
package com.lcc.dto; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.Transient; import com.lcc.utils.JsonUtils; import com.lcc.utils.MsgUtils; import org.codehaus.jackson.annotate.JsonIgnore; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; public class ActionResult { public static final Integer OK = 200; public static final Integer FAIL = 0; public static final Integer UNAUTH = 421; public static final Integer INVALID_ACTIVATION_CODE = 531; public static final Integer TRUCK_PLATE_ALREADY_REGISTERED = 532; public static final Integer CHOOSE_TRUCK_PLATE = -1; public static final Integer NO_TRUCK = -2; private int status = OK; private String message = "ok"; private Object data; private Map<String, Object> extendedData; public int getStatus() { return status; } @Transient public boolean isOK() { return OK == status; } public void setStatus(int status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = MsgUtils.get(message); } public Object getData() { return data; } @JsonIgnore @SuppressWarnings("unchecked") public <T> T getValue(String key) { if (data instanceof String) { return JsonUtils.get((String) data, key); } if (data instanceof JSONObject) { return JsonUtils.get((JSONObject) (data), key); } if (data instanceof Map) { return JsonUtils.get(new JSONObject((Map<String, Object>) data), key); } return null; } @JsonIgnore @SuppressWarnings("unchecked") public <T> T getDataEntity() { return (T) data; } public void setData(Object data) { this.data =http://www.mamicode.com/ data; } @JsonIgnore @Transient public Object getExtendedData() { return extendedData; } @SuppressWarnings("unchecked") public void setExtendedData(Object value) { if (value =http://www.mamicode.com/= null) { this.extendedData = http://www.mamicode.com/null; } else { if (value instanceof Map) { extendedData = (Map<String, Object>) value; } else { if (this.extendedData =http://www.mamicode.com/= null) { extendedData = new HashMap<String, Object>(3); } extendedData.put(String.valueOf(extendedData.size()), value); } } } public boolean hasExtendedData(String key) { if (extendedData =http://www.mamicode.com/= null) return false; return extendedData.containsKey(key); } public Object getExtendedData(String key) { if (extendedData =http://www.mamicode.com/= null) return null; return extendedData.get(key); } public void setExtendedData(String key, Object value) { if (extendedData =http://www.mamicode.com/= null) { extendedData = new HashMap<String, Object>(3); } extendedData.put(key, value); } public Object removeExtendedData(String key) { if (extendedData =http://www.mamicode.com/= null) { return null; } return extendedData.remove(key); } public void onFail(String message) { status = ActionResult.FAIL; this.message = MsgUtils.get(message); } public void onFail(JSONObject data) { status = ActionResult.FAIL; this.data =http://www.mamicode.com/ data; } public void onFail(List<?> data) { status = ActionResult.FAIL; this.data =http://www.mamicode.com/ data; } public static ActionResult fail(String message) { ActionResult result = new ActionResult(); result.onFail(message); return result; } public void onOK(Object data) { status = ActionResult.OK; message = "ok"; this.data =http://www.mamicode.com/ data; } public static ActionResult ok(Object data) { ActionResult result = new ActionResult(); result.onOK(data); return result; } public static ActionResult ok() { ActionResult result = new ActionResult(); return result; } public static ActionResult unauth() { ActionResult result = new ActionResult(); result.setStatus(UNAUTH); result.message = "您未登录或未授权。"; return result; } public static ActionResult build(int status, String message, Object data) { ActionResult result = new ActionResult(); result.status = status; result.message = MsgUtils.get(message); result.data = data; return result; } @Override public String toString() { return JSON.toJSONString(this); } }
ActionResult类里面用到的JsonUtils--------里面的main方法为测试
package com.lcc.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public class JsonUtils { private static Logger LOGGER = LoggerFactory.getLogger(JsonUtils.class); public static boolean has(JSONObject json, String fullPath) { try { String[] paths = fullPath.split("\\s*\\.\\s*"); int len = paths.length; String path; String key; Object current = json; for (int i = 0; i < len; i++) { path = paths[i]; if (path.isEmpty()) { continue; } if (path.endsWith("]")) { int index = path.indexOf("["); key = path.substring(0, index); current = ((JSONObject) current).get(key); path = path.substring(index + 1); String[] indice = path.replace("[", "").split("\\]"); for (String indx : indice) { if (indx.isEmpty()) { continue; } int i_indx = Integer.valueOf(indx); if (i_indx >= ((JSONArray) current).size()) { return false; } if (i_indx < 0 && ((JSONArray) current).size() + i_indx < 0) { return false; } if (i_indx < 0) { i_indx = ((JSONArray) current).size() + i_indx; } current = ((JSONArray) current).get(i_indx); } } else { key = path; if (!((JSONObject) current).containsKey(key)) { return false; } current = ((JSONObject) current).get(key); } } return true; } catch (Exception e) { LOGGER.error("Error raised when extract the object " + json + ", the path is " + fullPath, e); return false; } } public static <T> T get(String json, String fullPath) { return get(JSON.parseObject(json), fullPath); } @SuppressWarnings("unchecked") public static <T> T get(JSONObject json, String fullPath) { try { String[] paths = fullPath.split("\\s*\\.\\s*"); int len = paths.length; String path; String key; Object current = json; for (int i = 0; i < len; i++) { path = paths[i]; if (path.isEmpty()) { continue; } if (path.endsWith("]")) { int index = path.indexOf("["); key = path.substring(0, index); current = ((JSONObject) current).get(key); path = path.substring(index + 1); String[] indice = path.replace("[", "").split("\\]"); for (String indx : indice) { if (indx.isEmpty()) { continue; } int i_indx = Integer.valueOf(indx); if (i_indx < 0) { i_indx = ((JSONArray) current).size() + i_indx; } current = ((JSONArray) current).get(i_indx); } } else { key = path; current = ((JSONObject) current).get(key); } } return (T) current; } catch (Exception e) { LOGGER.error("Error raised when extract the object " + json + ", the path is " + fullPath, e); return null; } } public static void main(String[] args) { String content = "{\"user\":{\"name\":\"jay\",\"age\":30,\"favorite\":[\"篮球\",\"编程\",[{\"name\":\"吃饭\"},{\"name\":\"睡觉\"}]]}}"; JSONObject json = JSON.parseObject(content); System.out.println("content is " + json.toJSONString()); System.out.println("user.name is " + JsonUtils.get(json, "user.name")); System.out.println("user.age is " + JsonUtils.get(json, "user.age")); System.out.println("user.favorite is " + JsonUtils.get(json, "user.favorite")); System.out.println("user.favorite[0] is " + JsonUtils.get(json, "user.favorite[0]")); System.out.println("user.favorite[2][1] is " + JsonUtils.get(json, "user.favorite[2][1]")); System.out.println("user.favorite[2][1].name is " + JsonUtils.get(json, "user.favorite[2][1].name")); System.out.println("user.favorite[-1][1].name is " + JsonUtils.get(json, "user.favorite[-1][1].name")); System.out.println("user.favorite[-1][-1].name is " + JsonUtils.get(json, "user.favorite[-1][-1].name")); System.out.println("user.favorite[-1][-2].name is " + JsonUtils.get(json, "user.favorite[-1][-2].name")); System.out.println( "Is content contains user.favorite[-1][-2].name? " + JsonUtils.has(json, "user.favorite[-1][-2].name")); } }
ActionResult里面用到的MsgUtils
package com.lcc.utils; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.support.RequestContext; import org.springframework.web.servlet.support.RequestContextUtils; /** * Message utils for i18n */ public class MsgUtils { public static final String EXP_MSG = "\\$\\{([^}]*)\\}"; public static final String get(String key) { if (!key.matches(EXP_MSG)) return key; HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .getRequest(); RequestContext requestContext = new RequestContext(request); String pureKey = key.substring(2, key.length() - 1).trim(); try { return requestContext.getMessage(pureKey); } catch (Exception e) { } return ""; } public static final String get(String key, String defaultValue) { String value = get(key); return value.isEmpty() ? get(defaultValue) : value; } public static final String get(String key, String defaultValue1, String defaultValue2) { String value = get(key); return value.isEmpty() ? get(defaultValue1, defaultValue2) : value; } public static final String get(String key, String... args) { String msg = get(key); if (args != null && args.length > 0) { for (String arg : args) { msg = msg.replace(msg, get(arg)); } } return msg; } public static Locale getLocale() { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .getRequest(); return RequestContextUtils.getLocaleResolver(request).resolveLocale(request); } }
java发送http的get、post请求
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。