http post请求

来源:互联网 发布:南京江宁区网络问政 编辑:程序博客网 时间:2024/05/22 02:07
import java.awt.image.BufferedImage;import java.io.BufferedOutputStream;import java.io.ByteArrayOutputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URI;import java.util.UUID;import javax.imageio.ImageIO;import net.sf.json.JSONObject;import org.apache.commons.io.IOUtils;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.http.Header;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ByteArrayEntity;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.springframework.stereotype.Service;import com.wasu.login.exceptions.UpmException;import com.wasu.login.service.UpmBaseResponseManager;import com.wasu.login.util.ClientCrypt;import com.wasu.login.util.GlobalInfo;public class HttpclientConnectUtil {/** *获取返回信息 * @param url * @param body * @param msgCode * @param encryptV * @param publicKey * @return */@SuppressWarnings("static-access")public JSONObject getResponse2(String url, String body, String msgCode, String encryptV, String publicKey) {byte[] bodyByte = new byte[0];JSONObject returnMsg = new JSONObject();HttpURLConnection conn = null;InputStream is = null;try {conn = (HttpURLConnection) new URI(url).toURL().openConnection();if(encryptV.equals("0")) {bodyByte = body.getBytes("UTF-8");} else {bodyByte = ClientCrypt.encrypt(body.getBytes("UTF-8"), publicKey);}conn.setRequestMethod("POST");conn.setDoOutput(true);conn.setRequestProperty("Accept-Charset", "UTF-8");conn.setRequestProperty("Content-Type", GlobalInfo.CONTENT_TYPE);conn.setRequestProperty("Msg", msgCode);conn.setRequestProperty("uuid", UUID.randomUUID().toString());conn.setRequestProperty("V", encryptV);conn.setConnectTimeout(GlobalInfo.CONNECTTIMEOUT_NUMBER);  conn.setReadTimeout(GlobalInfo.READTIMEOUT_NUMBER); conn.getOutputStream().write(bodyByte);is = conn.getInputStream();byte[] resp = toByteArray(is);if(!encryptV.equals("0")) {resp = ClientCrypt.decrypt(resp, publicKey);}returnMsg =  returnMsg.fromObject(new String(resp, "utf-8"));} catch (Exception e) {} finally {IOUtils.closeQuietly(is);try{if(null != conn) conn.disconnect();}catch(Exception e) {}}return returnMsg;}/** *  * @param url * @param body * @param msgCode * @param encryptV * @param publicKey * @return */public JSONObject getResponse(String url, String body, String msgCode,String encryptV, String publicKey, String realIp) {JSONObject returnMsg = new JSONObject();CloseableHttpClient client = null;HttpPost httpPost = null;byte[] bodyByte = new byte[0];try {if (encryptV.equals("0")) {bodyByte = body.getBytes("UTF-8");} else {bodyByte = ClientCrypt.encrypt(body.getBytes("UTF-8"),publicKey);}client = HttpClients.createDefault();httpPost = new HttpPost(url);httpPost.setHeader("Content-Type", GlobalInfo.CONTENT_TYPE);httpPost.setHeader("Msg", msgCode);httpPost.setHeader("uuid", UUID.randomUUID().toString());httpPost.setHeader("V", encryptV);httpPost.setHeader("real_ip", realIp);ByteArrayEntity entity = new ByteArrayEntity(bodyByte);httpPost.setEntity(entity);RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(GlobalInfo.READTIMEOUT_NUMBER).setConnectTimeout(GlobalInfo.CONNECTTIMEOUT_NUMBER).build();httpPost.setConfig(requestConfig);HttpResponse response = client.execute(httpPost);int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) {byte[] resp = toByteArray(response.getEntity().getContent());if (!encryptV.equals("0")) {resp = ClientCrypt.decrypt(resp, publicKey);}returnMsg = JSONObject.fromObject(new String(resp, "utf-8"));} else {returnMsg.put("code", statusCode);returnMsg.put("description", GlobalInfo.RUNTIME_EXCEPTION_MSG);}} catch (Exception e) {} finally {try {if (null != httpPost)httpPost.releaseConnection();} catch (Exception e) {}try {if (null != client)client.close();} catch (Exception e) {}}return returnMsg;}/** * 获取支付宝登录二维码 * @param url * @return */public static JSONObject alipayLoginConnect(String url){JSONObject returnMsg = new JSONObject();CloseableHttpClient client = null;HttpPost httpPost = null;try {client = HttpClients.createDefault();httpPost = new HttpPost(url);RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(GlobalInfo.READTIMEOUT_NUMBER).setConnectTimeout(GlobalInfo.CONNECTTIMEOUT_NUMBER).build();httpPost.setConfig(requestConfig);HttpResponse response = client.execute(httpPost);Header header = response.getFirstHeader("uid");String uid = header.getValue();int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) {returnMsg.put("code", GlobalInfo.RETURN_CODE_SUCCESS);returnMsg.put("decription", GlobalInfo.REQUEST_NAME_ALIPAY_LOGIN_QRCODE);returnMsg.put("uid", uid);returnMsg.put("qrcode", getImageBinary(response.getEntity().getContent()));} else {returnMsg.put("coe", statusCode);returnMsg.put("description", GlobalInfo.RUNTIME_EXCEPTION_MSG);returnMsg.put("uid", "");returnMsg.put("qrode", "");}} catch (Exception e) {throw new UpmException(GlobalInfo.REQUEST_CODE_ALIPAY_LOGIN_QRCODE, e);} finally {try {if (null != httpPost)httpPost.releaseConnection();} catch (Exception e) {}try {if (null != client)client.close();} catch (Exception e) {}}return returnMsg;}public static byte[] toByteArray(InputStream input) throws IOException {ByteArrayOutputStream output = new ByteArrayOutputStream();copy(input, output);return output.toByteArray();}public static String getAppContextPath(){  String classPath = HttpclientConnectUtil.class.getResource("").getPath();  return classPath.substring(0,classPath.indexOf("new_login")); } public static String save(byte[] bit, String path) throws Exception {          BufferedOutputStream out = null;        path = path+"/qrcode.jpg";        if (bit.length > 0) {              try {                  out = new BufferedOutputStream(new FileOutputStream(path));                  out.write(bit);                  out.flush();            } finally {                  if (out != null)                      out.close();              }          }          return path;    }  public static int copy(InputStream input, OutputStream output) throws IOException {long count = copyLarge(input, output);if (count > 2147483647L) {return -1;}return (int)count;}static String getImageBinary(InputStream in){            BufferedImage bi;            try {                bi = ImageIO.read(in);                ByteArrayOutputStream baos = new ByteArrayOutputStream();                ImageIO.write(bi, "jpg", baos);                byte[] bytes = baos.toByteArray();                                return Base64Utils.encode(bytes).trim();            } catch (Exception e) {                e.printStackTrace();            }            return null;        }    public static long copyLarge(InputStream input, OutputStream output) throws IOException {byte[] buffer = new byte[4096];long count = 0L;int n = 0;while (-1 != (n = input.read(buffer))) {output.write(buffer, 0, n);count += n;}return count;}/** * post * @param url * @param value * @return */public static JSONObject getJsonPost(String url, String value){CloseableHttpClient client = null;JSONObject jb = new JSONObject();try {client = HttpClients.createDefault();HttpPost httpPost = new HttpPost(url);StringEntity se = new StringEntity(value);httpPost.setEntity(se);RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();//设置请求和传输超时时间httpPost.setConfig(requestConfig);HttpResponse response = client.execute(httpPost);HttpEntity entity = response.getEntity();if (entity != null) {jb = JSONObject.fromObject(EntityUtils.toString(entity, "UTF-8"));            }} catch (Exception e) {} finally{try {client.close();} catch (IOException e) {} }return jb;}/** * 解析返回json * @param url * @return */public static JSONObject getJsonGet(String url){CloseableHttpClient client = null;JSONObject jb = null;try {        client = HttpClients.createDefault();HttpGet httpget = new HttpGet(url);        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();//设置请求和传输超时时间httpget.setConfig(requestConfig);HttpResponse response = client.execute(httpget);HttpEntity entity = response.getEntity();if (entity != null) {jb = JSONObject.fromObject(EntityUtils.toString(entity, "UTF-8"));            }} catch (Exception e) {} finally{try {client.close();} catch (IOException e) {} }return jb;}/** * 解析返回String * @param url * @return */public  String getStringGet(String url){CloseableHttpClient client = null;String returnUrl = null;try {client = HttpClients.createDefault();HttpGet httpget = new HttpGet(url);RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();//设置请求和传输超时时间httpget.setConfig(requestConfig);HttpResponse response = client.execute(httpget);HttpEntity entity = response.getEntity();if (entity != null) {returnUrl = EntityUtils.toString(entity, "UTF-8");}} catch (Exception e) {logger.error("接口调用失败:"+e);} finally{try {client.close();} catch (IOException e) {} }return returnUrl;}
}

0 0
原创粉丝点击