Chinaunix首页 | 论坛 | 博客
  • 博客访问: 164960
  • 博文数量: 56
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 593
  • 用 户 组: 普通用户
  • 注册时间: 2014-02-18 09:59
文章分类

全部博文(56)

文章存档

2019年(1)

2018年(26)

2016年(1)

2015年(6)

2014年(22)

我的朋友

分类: Java

2018-06-29 15:30:42


这个应该是最实用的工具类之一了

这个HttpUtil工具类写的还是比较全面的, 日常使用中的使用场景都涵盖了
文件上传, json上传,  xml上传, form上传等, 使用方便性能大为提高

包含:
  • 发送GET请求
  • 发送GET请求 包含map参数
  • 发送GET请求  包含"map参数"和"请求属性"
  • 发送POST请求
  • 发送POST请求 包含map参数
  • 发送POST请求 包含"map参数"和"请求属性"
  • 发送请求, 得到响应对象 HttpRespons
  • 直接通过HTTP协议提交数据到服务器,实现面表单提交功能,  包含文件上传
  • 发送xml数据
  • 发送 Json数据



点击(此处)折叠或打开

  1. import java.io.BufferedReader;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStream;
  7. import java.io.OutputStreamWriter;
  8. import java.net.HttpURLConnection;
  9. import java.net.InetAddress;
  10. import java.net.Socket;
  11. import java.net.URL;
  12. import java.net.URLConnection;
  13. import java.net.URLEncoder;
  14. import java.nio.charset.Charset;
  15. import java.util.List;
  16. import java.util.Map;
  17. import java.util.Map.Entry;
  18. import java.util.Set;
  19. import java.util.Vector;

  20. import org.apache.http.HttpStatus;
  21. import org.apache.http.client.config.RequestConfig;
  22. import org.apache.http.client.methods.CloseableHttpResponse;
  23. import org.apache.http.client.methods.HttpPost;
  24. import org.apache.http.entity.mime.MultipartEntityBuilder;
  25. import org.apache.http.impl.client.CloseableHttpClient;
  26. import org.apache.http.impl.client.HttpClients;
  27. import org.apache.http.util.EntityUtils;
  28. import org.mogujie.iip.commons.pojo.FormFile;
  29. import org.mogujie.iip.commons.pojo.HttpRespons;

  30. import com.alibaba.fastjson.JSON;

  31. /**
  32.  * Created by fengzhen on 16/6/27.
  33.  */
  34. public class HttpUtil {

  35.     private String defaultContentEncoding;

  36.     public HttpUtil() {
  37.         this.defaultContentEncoding = Charset.defaultCharset().name();
  38.     }

  39.     /**
  40.      * 发送GET请求
  41.      *
  42.      * @param urlString URL地址
  43.      * @return 响应对象
  44.      * @throws IOException
  45.      */
  46.     public HttpRespons sendGet(String urlString) throws IOException {
  47.         return this.send(urlString, "GET", null, null);
  48.     }

  49.     /**
  50.      * 发送GET请求
  51.      *
  52.      * @param urlString URL地址
  53.      * @param params 参数集合
  54.      * @return 响应对象
  55.      * @throws IOException
  56.      */
  57.     public HttpRespons sendGet(String urlString, Map<String, String> params) throws IOException {
  58.         return this.send(urlString, "GET", params, null);
  59.     }

  60.     /**
  61.      * 发送GET请求
  62.      *
  63.      * @param urlString URL地址
  64.      * @param params 参数集合
  65.      * @param propertys 请求属性
  66.      * @return 响应对象
  67.      * @throws IOException
  68.      */
  69.     public HttpRespons sendGet(String urlString, Map<String, String> params, Map<String, String> propertys)
  70.             throws IOException {
  71.         return this.send(urlString, "GET", params, propertys);
  72.     }

  73.     /**
  74.      * 发送POST请求
  75.      *
  76.      * @param urlString URL地址
  77.      * @return 响应对象
  78.      * @throws IOException
  79.      */
  80.     public HttpRespons sendPost(String urlString) throws IOException {
  81.         return this.send(urlString, "POST", null, null);
  82.     }

  83.     /**
  84.      * 发送POST请求
  85.      *
  86.      * @param urlString URL地址
  87.      * @param params 参数集合
  88.      * @return 响应对象
  89.      * @throws IOException
  90.      */
  91.     public HttpRespons sendPost(String urlString, Map<String, String> params) throws IOException {
  92.         return this.send(urlString, "POST", params, null);
  93.     }

  94.     /**
  95.      * 发送POST请求
  96.      *
  97.      * @param urlString URL地址
  98.      * @param params 参数集合
  99.      * @param propertys 请求属性
  100.      * @return 响应对象
  101.      * @throws IOException
  102.      */
  103.     public HttpRespons sendPost(String urlString, Map<String, String> params, Map<String, String> propertys)
  104.             throws IOException {
  105.         return this.send(urlString, "POST", params, propertys);
  106.     }

  107.     /**
  108.      * 发送HTTP请求
  109.      *
  110.      * @param urlString 地址
  111.      * @param method get/post
  112.      * @param parameters 添加由键值对指定的请求参数
  113.      * @param propertys 添加由键值对指定的一般请求属性
  114.      * @return 响映对象
  115.      * @throws IOException
  116.      */
  117.     private HttpRespons send(String urlString, String method, Map<String, String> parameters,
  118.                              Map<String, String> propertys) throws IOException {
  119.         HttpURLConnection urlConnection = null;

  120.         if (method.equalsIgnoreCase("GET") && parameters != null) {
  121.             StringBuffer param = new StringBuffer();
  122.             int i = 0;
  123.             for (String key : parameters.keySet()) {
  124.                 if (i == 0)
  125.                     param.append("?");
  126.                 else
  127.                     param.append("&");
  128.                 param.append(key).append("=").append(parameters.get(key));
  129.                 i++;
  130.             }
  131.             urlString += param;
  132.         }

  133.         URL url = new URL(urlString);
  134.         urlConnection = (HttpURLConnection) url.openConnection();
  135.         urlConnection.setRequestMethod(method);
  136.         urlConnection.setDoOutput(true);
  137.         urlConnection.setDoInput(true);
  138.         urlConnection.setUseCaches(false);

  139.         if (propertys != null)
  140.             for (String key : propertys.keySet()) {
  141.                 urlConnection.addRequestProperty(key, propertys.get(key));
  142.             }

  143.         if (method.equalsIgnoreCase("POST") && parameters != null) {
  144.             StringBuffer param = new StringBuffer();
  145.             for (String key : parameters.keySet()) {
  146.                 param.append("&");
  147.                 param.append(key).append("=").append(parameters.get(key));
  148.             }
  149.             urlConnection.getOutputStream().write(param.toString().getBytes());
  150.             urlConnection.getOutputStream().flush();
  151.             urlConnection.getOutputStream().close();
  152.         }
  153.         return makeContent(urlString, urlConnection);
  154.     }

  155.     private static HttpRespons makeContent(String urlString, HttpURLConnection urlConnection) throws IOException {
  156.         return makeContent(urlString, urlConnection, null);
  157.     }

  158.     /**
  159.      * 得到响应对象
  160.      *
  161.      * @param urlConnection
  162.      * @return 响应对象
  163.      * @throws IOException
  164.      */
  165.     private static HttpRespons makeContent(String urlString, HttpURLConnection urlConnection, String ecod) throws IOException {
  166.         HttpRespons httpResponser = new HttpRespons();
  167.         try {
  168.             InputStream in = urlConnection.getInputStream();
  169.             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
  170.             List<String> contentCollection = new Vector<String>();
  171.             StringBuffer temp = new StringBuffer();
  172.             String line = bufferedReader.readLine();
  173.             while (line != null) {
  174.                 contentCollection.add(line);
  175.                 temp.append(line).append("\r\n");
  176.                 line = bufferedReader.readLine();
  177.             }
  178.             bufferedReader.close();
  179.             if(StringUtil.isEmpty(ecod)) {
  180.                 ecod = urlConnection.getContentEncoding();
  181.                 if (ecod == null)
  182.                     ecod = "UTF-8";
  183.             }
  184.             httpResponser.setUrlString(urlString);
  185.             httpResponser.setDefaultPort(urlConnection.getURL().getDefaultPort());
  186.             httpResponser.setFile(urlConnection.getURL().getFile());
  187.             httpResponser.setHost(urlConnection.getURL().getHost());
  188.             httpResponser.setPath(urlConnection.getURL().getPath());
  189.             httpResponser.setPort(urlConnection.getURL().getPort());
  190.             httpResponser.setProtocol(urlConnection.getURL().getProtocol());
  191.             httpResponser.setQuery(urlConnection.getURL().getQuery());
  192.             httpResponser.setRef(urlConnection.getURL().getRef());
  193.             httpResponser.setUserInfo(urlConnection.getURL().getUserInfo());
  194.             httpResponser.setContent(new String(temp.toString().getBytes(), ecod));
  195.             httpResponser.setContentEncoding(ecod);
  196.             httpResponser.setCode(urlConnection.getResponseCode());
  197.             httpResponser.setMessage(urlConnection.getResponseMessage());
  198.             httpResponser.setContentType(urlConnection.getContentType());
  199.             httpResponser.setMethod(urlConnection.getRequestMethod());
  200.             httpResponser.setConnectTimeout(urlConnection.getConnectTimeout());
  201.             httpResponser.setReadTimeout(urlConnection.getReadTimeout());
  202.             return httpResponser;
  203.         } catch (IOException e) {
  204.             throw e;
  205.         } finally {
  206.             if (urlConnection != null)
  207.                 urlConnection.disconnect();
  208.         }
  209.     }

  210.     /**
  211.      * 默认的响应字符集
  212.      */
  213.     public String getDefaultContentEncoding() {
  214.         return this.defaultContentEncoding;
  215.     }


  216.     /**
  217.      * 发送GET请求
  218.      * @param url
  219.      * @param params
  220.      * @param headers
  221.      * @return
  222.      * @throws Exception
  223.      */
  224.     public static URLConnection sendGetRequest(String url,
  225.                                                Map<String, String> params, Map<String, String> headers)
  226.             throws Exception {
  227.         StringBuilder buf = new StringBuilder(url);
  228.         Set<Entry<String, String>> entrys = null;
  229.         // 如果是GET请求,则请求参数在URL中
  230.         if (params != null && !params.isEmpty()) {
  231.             buf.append("?");
  232.             entrys = params.entrySet();
  233.             for (Map.Entry<String, String> entry : entrys) {
  234.                 buf.append(entry.getKey()).append("=")
  235.                         .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
  236.                         .append("&");
  237.             }
  238.             buf.deleteCharAt(buf.length() - 1);
  239.         }
  240.         URL url1 = new URL(buf.toString());
  241.         HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
  242.         conn.setRequestMethod("GET");
  243.         // 设置请求头
  244.         if (headers != null && !headers.isEmpty()) {
  245.             entrys = headers.entrySet();
  246.             for (Map.Entry<String, String> entry : entrys) {
  247.                 conn.setRequestProperty(entry.getKey(), entry.getValue());
  248.             }
  249.         }
  250.         conn.getResponseCode();
  251.         return conn;
  252.     }
  253.     /**
  254.      * 发送POST请求
  255.      * @param url
  256.      * @param params
  257.      * @param headers
  258.      * @return
  259.      * @throws Exception
  260.      */
  261.     public static URLConnection sendPostRequest(String url,
  262.                                                 Map<String, String> params, Map<String, String> headers)
  263.             throws Exception {
  264.         StringBuilder buf = new StringBuilder();
  265.         Set<Entry<String, String>> entrys = null;
  266.         // 如果存在参数,则放在HTTP请求体,形如name=aaa&age=10
  267.         if (params != null && !params.isEmpty()) {
  268.             entrys = params.entrySet();
  269.             for (Map.Entry<String, String> entry : entrys) {
  270.                 buf.append(entry.getKey()).append("=")
  271.                         .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
  272.                         .append("&");
  273.             }
  274.             buf.deleteCharAt(buf.length() - 1);
  275.         }
  276.         URL url1 = new URL(url);
  277.         HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
  278.         conn.setRequestMethod("POST");
  279.         conn.setDoOutput(true);
  280.         OutputStream out = conn.getOutputStream();
  281.         out.write(buf.toString().getBytes("UTF-8"));
  282.         if (headers != null && !headers.isEmpty()) {
  283.             entrys = headers.entrySet();
  284.             for (Map.Entry<String, String> entry : entrys) {
  285.                 conn.setRequestProperty(entry.getKey(), entry.getValue());
  286.             }
  287.         }
  288.         conn.getResponseCode(); // 为了发送成功
  289.         return conn;
  290.     }
  291.     /**
  292.      * 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能:
  293.      *

  294.      
  295.      
  296.      
  297.      
  298.      
  299.      * @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用或这样的路径测试)
  300.      * @param params 请求参数 key为参数名,value为参数值
  301.      * @param files 上传文件
  302.      */
  303.     public static boolean uploadFiles(String path, Map<String, String> params, FormFile[] files) throws Exception{
  304.         final String BOUNDARY = "---------------------------7da2137580612"; //数据分隔线
  305.         final String endline = "--" + BOUNDARY + "--\r\n";//数据结束标志

  306.         int fileDataLength = 0;
  307.         if(files!=null&&files.length!=0){
  308.             for(FormFile uploadFile : files){//得到文件类型数据的总长度
  309.                 StringBuilder fileExplain = new StringBuilder();
  310.                 fileExplain.append("--");
  311.                 fileExplain.append(BOUNDARY);
  312.                 fileExplain.append("\r\n");
  313.                 fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
  314.                 fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
  315.                 fileExplain.append("\r\n");
  316.                 fileDataLength += fileExplain.length();
  317.                 if(uploadFile.getInStream()!=null){
  318.                     fileDataLength += uploadFile.getFile().length();
  319.                 }else{
  320.                     fileDataLength += uploadFile.getData().length;
  321.                 }
  322.             }
  323.         }
  324.         StringBuilder textEntity = new StringBuilder();
  325.         if(params!=null&&!params.isEmpty()){
  326.             for (Map.Entry<String, String> entry : params.entrySet()) {//构造文本类型参数的实体数据
  327.                 textEntity.append("--");
  328.                 textEntity.append(BOUNDARY);
  329.                 textEntity.append("\r\n");
  330.                 textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
  331.                 textEntity.append(entry.getValue());
  332.                 textEntity.append("\r\n");
  333.             }
  334.         }
  335.         //计算传输给服务器的实体数据总长度
  336.         int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length;

  337.         URL url = new URL(path);
  338.         int port = url.getPort()==-1 ? 80 : url.getPort();
  339.         Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
  340.         OutputStream outStream = socket.getOutputStream();
  341.         //下面完成HTTP请求头的发送
  342.         String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n";
  343.         outStream.write(requestmethod.getBytes());
  344.         String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
  345.         outStream.write(accept.getBytes());
  346.         String language = "Accept-Language: zh-CN\r\n";
  347.         outStream.write(language.getBytes());
  348.         String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n";
  349.         outStream.write(contenttype.getBytes());
  350.         String contentlength = "Content-Length: "+ dataLength + "\r\n";
  351.         outStream.write(contentlength.getBytes());
  352.         String alive = "Connection: Keep-Alive\r\n";
  353.         outStream.write(alive.getBytes());
  354.         String host = "Host: "+ url.getHost() +":"+ port +"\r\n";
  355.         outStream.write(host.getBytes());
  356.         //写完HTTP请求头后根据HTTP协议再写一个回车换行
  357.         outStream.write("\r\n".getBytes());
  358.         //把所有文本类型的实体数据发送出来
  359.         outStream.write(textEntity.toString().getBytes());
  360.         //把所有文件类型的实体数据发送出来
  361.         if(files!=null&&files.length!=0){
  362.             for(FormFile uploadFile : files){
  363.                 StringBuilder fileEntity = new StringBuilder();
  364.                 fileEntity.append("--");
  365.                 fileEntity.append(BOUNDARY);
  366.                 fileEntity.append("\r\n");
  367.                 fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
  368.                 fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
  369.                 outStream.write(fileEntity.toString().getBytes());
  370.                 if(uploadFile.getInStream()!=null){
  371.                     byte[] buffer = new byte[1024];
  372.                     int len = 0;
  373.                     while((len = uploadFile.getInStream().read(buffer, 0, 1024))!=-1){
  374.                         outStream.write(buffer, 0, len);
  375.                     }
  376.                     uploadFile.getInStream().close();
  377.                 }else{
  378.                     outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);
  379.                 }
  380.                 outStream.write("\r\n".getBytes());
  381.             }
  382.         }
  383.         //下面发送数据结束标志,表示数据已经结束
  384.         outStream.write(endline.getBytes());
  385.         BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  386.         
  387.         if(reader.readLine().indexOf("200")==-1){//读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败
  388.             outStream.flush();
  389.             outStream.close();
  390.             reader.close();
  391.             socket.close();
  392.             return false;
  393.         }
  394.         outStream.flush();
  395.         outStream.close();
  396.         reader.close();
  397.         socket.close();
  398.         return true;
  399.     }
  400.     /**
  401.      * 提交数据到服务器
  402.      * @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用或这样的路径测试)
  403.      * @param params 请求参数 key为参数名,value为参数值
  404.      * @param file 上传文件
  405.      */
  406.     public static boolean uploadFile(String path, Map<String, String> params, FormFile file) throws Exception{
  407.         return uploadFiles(path, params, new FormFile[]{file});
  408.     }
  409.     /**
  410.      * 将输入流转为字节数组
  411.      * @param inStream
  412.      * @return
  413.      * @throws Exception
  414.      */
  415.     public static byte[] read2Byte(InputStream inStream)throws Exception{
  416.         ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
  417.         byte[] buffer = new byte[1024];
  418.         int len = 0;
  419.         while( (len = inStream.read(buffer)) !=-1 ){
  420.             outSteam.write(buffer, 0, len);
  421.         }
  422.         outSteam.close();
  423.         inStream.close();
  424.         return outSteam.toByteArray();
  425.     }
  426.     /**
  427.      * 将输入流转为字符串
  428.      * @param inStream
  429.      * @return
  430.      * @throws Exception
  431.      */
  432.     public static String read2String(InputStream inStream)throws Exception{
  433.         ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
  434.         byte[] buffer = new byte[1024];
  435.         int len = 0;
  436.         while( (len = inStream.read(buffer)) !=-1 ){
  437.             outSteam.write(buffer, 0, len);
  438.         }
  439.         outSteam.close();
  440.         inStream.close();
  441.         return new String(outSteam.toByteArray(),"UTF-8");
  442.     }
  443.     /**
  444.      * 发送xml数据
  445.      * @param path 请求地址
  446.      * @param xml xml数据
  447.      * @param encoding 编码
  448.      * @return
  449.      * @throws Exception
  450.      */
  451.     public static byte[] postXml(String path, String xml, String encoding) throws Exception{
  452.         byte[] data = xml.getBytes(encoding);
  453.         URL url = new URL(path);
  454.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  455.         conn.setRequestMethod("POST");
  456.         conn.setDoOutput(true);
  457.         conn.setRequestProperty("Content-Type", "text/xml; charset="+ encoding);
  458.         conn.setRequestProperty("Content-Length", String.valueOf(data.length));
  459.         conn.setConnectTimeout(5 * 1000);
  460.         OutputStream outStream = conn.getOutputStream();
  461.         outStream.write(data);
  462.         outStream.flush();
  463.         outStream.close();
  464.         if(conn.getResponseCode()==200){
  465.             return read2Byte(conn.getInputStream());
  466.         }
  467.         return null;
  468.     }

  469.     /**
  470.      * 设置默认的响应字符集
  471.      */
  472.     public void setDefaultContentEncoding(String defaultContentEncoding) {
  473.         this.defaultContentEncoding = defaultContentEncoding;
  474.     }

  475.     /**
  476.      * 发送post请求
  477.      * @param url 地址
  478.      * @param params 参数
  479.      * @return 请求资源返回的值
  480.      */
  481.     public static String postForm(String url, Map<String, Object> params, int... timeout) {
  482.         String charset = "UTF-8";

  483.         CloseableHttpClient httpClient = HttpClients.createDefault();
  484.         HttpPost httpPost = new HttpPost(url);
  485.         int cTimeout = 3000;
  486.         // 设置请求和传输超时时间
  487.         if (timeout != null && timeout.length > 0) {
  488.             cTimeout = timeout[0];
  489.         }
  490.         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(cTimeout)
  491.                 .setConnectTimeout(cTimeout).build();
  492.         httpPost.setConfig(requestConfig);

  493.         CloseableHttpResponse httpResponse = null;
  494.         try {
  495.             if (params != null && params.isEmpty() == false) {

  496.                 MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  497.                 //builder.setCharset(Charset.forName(charset));

  498.                 if (params != null && !params.isEmpty()) {
  499.                     for (Map.Entry<String, Object> entry : params.entrySet()) {//构造文本类型参数的实体数据
  500.                         builder.addTextBody(entry.getKey(), entry.getValue().toString());//增加文本内容
  501.                     }
  502.                 }

  503.                 httpPost.setEntity(builder.build());
  504.             }

  505.             httpResponse = httpClient.execute(httpPost);
  506.             if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
  507.                 System.out.println(url + ": " + httpResponse.getStatusLine().getStatusCode());
  508.             }
  509.             return EntityUtils.toString(httpResponse.getEntity(), charset);
  510.         } catch (Exception ex) {
  511.             System.out.println(url);
  512.             System.out.println(JSON.toJSONString(params));
  513.             ex.printStackTrace();
  514.             return null;
  515.         } finally {
  516.             try {
  517.                 if (httpResponse != null) {
  518.                     httpResponse.close();
  519.                 }
  520.                 httpClient.close();
  521.             } catch (Exception ex) {
  522.                 System.out.println(url + ": " + ex.getMessage());
  523.             }
  524.         }
  525.     }

  526.     /**
  527.      * post Json
  528.      * @param strURL
  529.      * @param params
  530.      * @return
  531.      */
  532.     public static String postJSON(String strURL, Map<String, Object> params) {

  533.         String paramsStr = JSON.toJSONString(params);

  534.         try {
  535.             URL url = new URL(strURL);// 创建连接
  536.             HttpURLConnection connection = (HttpURLConnection) url
  537.                     .openConnection();
  538.             connection.setDoOutput(true);
  539.             connection.setDoInput(true);
  540.             connection.setUseCaches(false);
  541.             connection.setInstanceFollowRedirects(true);
  542.             connection.setRequestMethod("POST"); // 设置请求方式
  543.             connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
  544.             connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
  545.             connection.connect();
  546.             OutputStreamWriter out = new OutputStreamWriter(
  547.                     connection.getOutputStream(), "UTF-8"); // utf-8编码
  548.             out.append(paramsStr);
  549.             out.flush();
  550.             out.close();
  551.             // 读取响应
  552.             int length = (int) connection.getContentLength();// 获取长度
  553.             InputStream is = connection.getInputStream();
  554.             if (length != -1) {
  555.                 byte[] data = new byte[length];
  556.                 byte[] temp = new byte[512];
  557.                 int readLen = 0;
  558.                 int destPos = 0;
  559.                 while ((readLen = is.read(temp)) > 0) {
  560.                     System.arraycopy(temp, 0, data, destPos, readLen);
  561.                     destPos += readLen;
  562.                 }
  563.                 String result = new String(data, "UTF-8"); // utf-8编码
  564.                 System.out.println(result);
  565.                 return result;
  566.             }
  567.         } catch (IOException e) {
  568.             System.out.println(strURL);
  569.             System.out.println(paramsStr);
  570.             e.printStackTrace();
  571.         }
  572.         return "error"; // 自定义错误信息
  573.     }

  574.     public static String postUrl(String urlStr, Map<String, Object> params) {
  575.         return postUrl(urlStr, params, null);
  576.     }

  577.     /**
  578.      * post Url
  579.      * @param urlStr
  580.      * @param params
  581.      * @return
  582.      */
  583.     public static String postUrl(String urlStr, Map<String, Object> params, String encode) {

  584.         try {

  585.             URL url = new URL(urlStr);
  586.             HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  587.             urlConnection.setRequestMethod("POST");
  588.             urlConnection.setDoOutput(true);
  589.             urlConnection.setDoInput(true);
  590.             urlConnection.setUseCaches(false);

  591.             if (params != null) {

  592.                 StringBuffer param = new StringBuffer();

  593.                 for (String key : params.keySet()) {
  594.                     if(params.get(key) instanceof List){
  595.                         @SuppressWarnings("unchecked")
  596.                         List<Object> list = (List<Object>) params.get(key);
  597.                         for (Object str : list){
  598.                             param.append("&");
  599.                             param.append(key).append("=").append(str);
  600.                         }
  601.                     } else {
  602.                         param.append("&");
  603.                         param.append(key).append("=").append(params.get(key));
  604.                     }
  605.                 }

  606.                 urlConnection.getOutputStream().write(param.toString().getBytes());
  607.                 urlConnection.getOutputStream().flush();
  608.                 urlConnection.getOutputStream().close();
  609.             }

  610.             HttpRespons respons = makeContent(urlStr, urlConnection, encode);

  611.             if (respons.getCode() != 200) {
  612.                 System.out.println(urlStr);
  613.                 System.out.println(JSON.toJSONString(params));
  614.                 System.out.println(respons.getContent());
  615.             }

  616.             return respons.getContent();

  617.         } catch (Exception ex) {
  618.             System.out.println(urlStr);
  619.             System.out.println(JSON.toJSONString(params));
  620.             ex.printStackTrace();
  621.             return null;
  622.         }
  623.     }
  624. }

阅读(8548) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~