restful POST 和GET 请求

xiaoxiao2021-02-28  93

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; 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.entity.StringEntity; 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.slf4j.Logger; import org.slf4j.LoggerFactory; /**  * 调用 restfu 客户端工具  *   * @author 80002315  *  */ public class HttpUtil { private final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);     /**      * 向指定 URL 发送POST方法的请求      *       * @param url      *            发送请求的 URL      * @param param      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。      * @return 所代表远程资源的响应结果      */     public static String sendPost(String url,int timeout, String param) {         PrintWriter out = null;         BufferedReader in = null;         String result = "";         try {             URL realUrl = new URL(url);             // 打开和URL之间的连接             URLConnection conn = realUrl.openConnection();             //设置超时时间             conn.setConnectTimeout(timeout);             conn.setReadTimeout(timeout);             // 设置通用的请求属性             conn.setRequestProperty("accept", "*/*");             conn.setRequestProperty("connection", "Keep-Alive");             conn.setRequestProperty("user-agent",                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");             // 发送POST请求必须设置如下两行             conn.setDoOutput(true);             conn.setDoInput(true);             // 获取URLConnection对象对应的输出流             out = new PrintWriter(conn.getOutputStream());             // 发送请求参数             out.print(param);             // flush输出流的缓冲             out.flush();             // 定义BufferedReader输入流来读取URL的响应             in = new BufferedReader(                     new InputStreamReader(conn.getInputStream()));             String line;             while ((line = in.readLine()) != null) {                 result += line;             }         } catch (Exception e) {         logger.error(e.getMessage(), e);         }         //使用finally块来关闭输出流、输入流         finally{             try{                 if(out!=null){                     out.close();                 }                 if(in!=null){                     in.close();                 }             }             catch(IOException ex){             logger.error(ex.getMessage(), ex);             }         }         return result;     }         public static String sendPost(String url,String contentType,int timeout, String param) {         PrintWriter out = null;         BufferedReader in = null;         String result = "";         try {             URL realUrl = new URL(url);             // 打开和URL之间的连接             URLConnection conn = realUrl.openConnection();             //设置超时时间             conn.setConnectTimeout(timeout);             conn.setReadTimeout(timeout);             // 设置通用的请求属性             conn.setRequestProperty("accept", "*/*");             conn.setRequestProperty("connection", "Keep-Alive");             conn.setRequestProperty("user-agent",                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");             conn.setRequestProperty("Content-Type", contentType);             // 发送POST请求必须设置如下两行             conn.setDoOutput(true);             conn.setDoInput(true);             // 获取URLConnection对象对应的输出流             out = new PrintWriter(conn.getOutputStream());             // 发送请求参数             out.print(param);             // flush输出流的缓冲             out.flush();             // 定义BufferedReader输入流来读取URL的响应             in = new BufferedReader(                     new InputStreamReader(conn.getInputStream()));             String line;             while ((line = in.readLine()) != null) {                 result += line;             }         } catch (Exception e) {         logger.error(e.getMessage(), e);         }         //使用finally块来关闭输出流、输入流         finally{             try{                 if(out!=null){                     out.close();                 }                 if(in!=null){                     in.close();                 }             }             catch(IOException ex){             logger.error(ex.getMessage(), ex);             }         }         return result;     }         /**      * url 请求地址      * params 要提交的键值对数据      */     public static String sendPost(String url, String timeout,Map<String, String> params) {     String strParam = null;     StringBuilder sb = new StringBuilder();     try {     for(Entry<String, String> param : params.entrySet())         {         sb.append("&").append(param.getKey()).append("=").append(URLEncoder.encode(param.getValue(), "utf-8"));         } } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); }         //当长度大于0时截去第一个字符     if(sb.length()>0)     {     strParam = sb.substring(1);     }     String httpResult = null;     int times = 0;     while(times < 3)     {     try{     httpResult = post(url,"text/plain", strParam);     break;     }catch (Exception e) {     logger.error(e.getMessage(), e); }     }     return httpResult;     }          /**       * 发送HttpPost请求       *        * @param strURL       *            服务地址       * @param json      *            json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/>       * @return 成功:返回json字符串<br/>       */       public static String post(final String strURL,final  String json) {     return post(strURL, json, 4000, 6000);     }     /**      * 发送HttpPost请求      *      * @param strURL      *            服务地址      * @param json      *            json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/>      * @param connectTimeout 连接超时时间      * @param readTimeout 读取超时时间      * @return 成功:返回json字符串<br/>      */     public static String post(final String strURL,final  String json, final int connectTimeout, final int readTimeout) {         String error = "error";         try {             if(StringUtils.isBlank(strURL)||StringUtils.isBlank(json))             {                 logger.info("post---json---error:"+json);                 return error;             }             //System.out.println(strURL);             URL url = new URL(strURL);// 创建连接             HttpURLConnection connection = (HttpURLConnection) url                     .openConnection();             connection.setConnectTimeout(connectTimeout);             connection.setReadTimeout(readTimeout);             connection.setDoOutput(true);             connection.setDoInput(true);             connection.setUseCaches(false);             connection.setInstanceFollowRedirects(true);             connection.setRequestMethod("POST"); // 设置请求方式             connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式             connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式             connection.connect();             OutputStreamWriter out = new OutputStreamWriter(                     connection.getOutputStream(), "UTF-8"); // utf-8编码             out.append(json);             String ss = "";             out.write(ss);             //System.out.println(ss);             out.flush();             out.close();             // 读取响应             int length = (int) connection.getContentLength();// 获取长度             InputStream is = connection.getInputStream();             if (length != -1) {                 byte[] data = new byte[length];                 byte[] temp = new byte[512];                 int readLen = 0;                 int destPos = 0;                 while ((readLen = is.read(temp)) > 0) {                     System.arraycopy(temp, 0, data, destPos, readLen);                     destPos += readLen;                 }                 String result = new String(data, "UTF-8"); // utf-8编码                 logger.info("post---json---ok:"+json);                 logger.info(String.format("结束----------------post-------------------------调用前HttpUtil|jsonStr:%s",result));                 return result;             }         } catch (IOException e) {             // TODO Auto-generated catch block             //e.printStackTrace();             logger.error("error msg!", e);             return error;         }         logger.info("post---json---error:"+json);         return error; // 自定义错误信息     }          public static String post(final String strURL,final String mime, final  String json) {         String error = "error";         try {             if(StringUtils.isBlank(strURL)||StringUtils.isBlank(json))             {                 logger.info("post---json---error:"+json);                 return error;             }             System.out.println(strURL);             URL url = new URL(strURL);// 创建连接             HttpURLConnection connection = (HttpURLConnection) url                     .openConnection();             connection.setConnectTimeout(4000);             connection.setReadTimeout(6000);             connection.setDoOutput(true);             connection.setDoInput(true);             connection.setUseCaches(false);             connection.setInstanceFollowRedirects(true);             connection.setRequestMethod("POST"); // 设置请求方式             connection.setRequestProperty("Accept", mime); // 设置接收数据的格式             connection.setRequestProperty("Content-Type", mime); // 设置发送数据的格式             connection.connect();             OutputStreamWriter out = new OutputStreamWriter(                     connection.getOutputStream(), "UTF-8"); // utf-8编码             out.append(json);             String ss = "";             out.write(ss);             System.out.println(ss);             out.flush();             out.close();             // 读取响应             int length = (int) connection.getContentLength();// 获取长度             InputStream is = connection.getInputStream();             if (length != -1) {                 byte[] data = new byte[length];                 byte[] temp = new byte[512];                 int readLen = 0;                 int destPos = 0;                 while ((readLen = is.read(temp)) > 0) {                     System.arraycopy(temp, 0, data, destPos, readLen);                     destPos += readLen;                 }                 String result = new String(data, "UTF-8"); // utf-8编码                 logger.info("post---json---ok:"+json);                 return result;             }         } catch (IOException e) {             // TODO Auto-generated catch block             e.printStackTrace();             logger.error("post---json---error:"+json,e);             return error;         }         logger.info("post---json---error:"+json);         return error; // 自定义错误信息     }     /**      * request post use HttpClient      * @param url      * @param params      * @return      * @throws Throwable      */     public static String post(String url, final Map<String, String> params, int timeout) {         CloseableHttpResponse response = null;         try {             RequestConfig defaultRequestConfig = RequestConfig.custom()                     .setSocketTimeout(timeout)                     .setConnectTimeout(timeout)                     .setConnectionRequestTimeout(timeout)                     .build();             CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();             HttpPost httpPost = new HttpPost(url);             List<NameValuePair> nvps = new ArrayList <NameValuePair>();             for (Map.Entry<String, String> parameter : params.entrySet()) {                 nvps.add(new BasicNameValuePair(parameter.getKey(),parameter.getValue()));             }             httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));             response = httpclient.execute(httpPost);             HttpEntity entity = response.getEntity();             return EntityUtils.toString(entity, "UTF-8");         } catch (UnsupportedEncodingException e) {             logger.error(e.getMessage(), e);         } catch (ClientProtocolException e) {             logger.error(e.getMessage(), e);         } catch (IOException e) {             logger.error(e.getMessage(), e);         } finally {             if (response != null) {                 try {                     response.close();                 } catch (IOException e) {                    logger.error(e.getMessage(), e);                 }             }         }         return null;     }     /**      *      * @param uri      * @param params      * @param headers      * @return      * @throws ClientProtocolException      * @throws IOException      */     public static String post(String uri,Map<String, String> params,Map<String, String> headers,int timeout) {         HttpPost post = new HttpPost(uri);         CloseableHttpResponse response = null;         try{        RequestConfig config = RequestConfig.custom()         .setSocketTimeout(timeout)                .setConnectTimeout(timeout)                .setConnectionRequestTimeout(timeout)                .build();        CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();                for(String header : headers.keySet()){            post.addHeader(header,headers.get(header));        }        List<NameValuePair> paramList = new ArrayList<NameValuePair>();        for(Map.Entry<String, String> entry :params.entrySet()){            paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));        }        post.setEntity(new UrlEncodedFormEntity(paramList,"UTF-8"));        response = client.execute(post);        HttpEntity entity = response.getEntity();        return EntityUtils.toString(entity,"UTF-8");    } catch (UnsupportedEncodingException e) {        logger.error(e.getMessage(), e);    } catch (ClientProtocolException e) {        logger.error(e.getMessage(), e);    } catch (IOException e) {        logger.error(e.getMessage(), e);    } finally {        if (response != null) {            try {                response.close();            } catch (IOException e) {               logger.error(e.getMessage(), e);            }        }    }    return null;     }     /**      *request post use HttpClient  828471      * @param url      * @param params        json      * @param timeout      * @return      * @throws ClientProtocolException      * @throws IOException      */     public static String post(final String url, final String params,Map<String, String> headers, int timeout) {         CloseableHttpResponse response = null;         try {             RequestConfig defaultRequestConfig = RequestConfig.custom()                     .setSocketTimeout(timeout)                     .setConnectTimeout(timeout)                     .setConnectionRequestTimeout(timeout)                     .build();             CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();             HttpPost httpPost = new HttpPost(url); /*            List<NameValuePair> nvps = new ArrayList <NameValuePair>();             for (Map.Entry<String, String> parameter : params.entrySet()) {                 nvps.add(new BasicNameValuePair(parameter.getKey(),parameter.getValue()));             }*/             for(String header : headers.keySet()){                 httpPost.addHeader(header,headers.get(header));             }             httpPost.setEntity(new StringEntity(params, "UTF-8"));             response = httpclient.execute(httpPost);             HttpEntity entity = response.getEntity();             return EntityUtils.toString(entity, "UTF-8");         } catch (UnsupportedEncodingException e) {             logger.error(e.getMessage(), e);         } catch (ClientProtocolException e) {             logger.error(e.getMessage(), e);         } catch (IOException e) {             logger.error(e.getMessage(), e);         } finally {             if (response != null) {                 try {                     response.close();                 } catch (IOException e) {                     logger.error(e.getMessage(), e);                 }             }         }         return null;     }         public static void main(String[] args) { Map<String,String> paramMap=new HashMap<String,String>(); paramMap.put("TRSF_NO", "755255821112"); paramMap.put("QRY_TYPE", "2"); paramMap.put("CUST_PAY_MOBILE", "13713689436"); Map<String,String> headMap=new HashMap<String,String>(); headMap.put("Content-Type", "application/json"); System.out.println(JsonUtils.toJson(paramMap)); String url="http://10.202.37.140:8080/pub/qryTransfItem"; Map<String,String> map=new HashMap<String,String>(); map.put("Content-Type", "application/json"); String ss=post(url, JsonUtils.toJson(paramMap),map,1000*20); System.out.println(ss); } }
转载请注明原文地址: https://www.6miu.com/read-83982.html

最新回复(0)