java的post网络请求

public class HttpsUtil
{

   // 超时时间单位毫秒
   private static final int TIME_OUT = 1000 * 2;
   // 提交方法POST
   private static final String METHOD_POST = "POST";
   // 提交方法GET
   private static final String METHOD_GET = "GET";
   // 字符集
   private static final String Encoding_UTF8 = "UTF-8";
   // 返回状态码
   private static final Integer HTTP_OK = 200;

   private static class TrustAnyTrustManager implements X509TrustManager
   {
      // 检查客户端信任
      public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException
      {
      }

      // 检查服务端信任
      public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException
      {
      }

      // x509证书
      public X509Certificate[] getAcceptedIssuers()
      {
         return new X509Certificate[] {};
      }
   }

   // 任何信任主机名验证
   private static class TrustAnyHostnameVerifier implements HostnameVerifier
   {
      public boolean verify(String hostname, SSLSession session)
      {
         return true;
      }
   }

   public static void main(String[] args) throws Exception
   {
      String s = "";
      // post("https://www.hao123.com",s,"UTF-8");
      System.out.println(post("https://xxx", s));
   }

   /**
    * post方式请求服务器(https协议)
    *
    * @param url
    *            请求地址
    * @param content
    *            参数
    * @param charset
    *            编码
    * @return
    * @throws NoSuchAlgorithmException
    * @throws KeyManagementException
    * @throws IOException
    */
   public static byte[] post(String url, String content, String charset) throws NoSuchAlgorithmException, KeyManagementException, IOException
   {
      // 获得SSL实例
      SSLContext sc = SSLContext.getInstance("SSL");
      // SSL实例初始化
      sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
      // 创建URL对象
      URL console = new URL(url);
      // URL对象转换成httpsURLConnection对象(直接强转)
      HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
      // 设置httpsURL连接
      conn.setSSLSocketFactory(sc.getSocketFactory());
      // 设置连接主机名验证器
      conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
      conn.setDoOutput(true);
      // 设置连接超时时间
      conn.setConnectTimeout(TIME_OUT);
      // 设置是否使用缓存
      conn.setUseCaches(true);
      // 设置连接请求的方法类型
      conn.setRequestMethod(METHOD_POST);
      // 设置连接请求的属性(字符集为UTF-8)
      conn.setRequestProperty("charset", "UTF-8");
      // 建立连接
      conn.connect();
      DataOutputStream out = new DataOutputStream(conn.getOutputStream());
      out.write(content.getBytes(charset));
      // 刷新、关闭
      out.flush();
      out.close();
      InputStream is = conn.getInputStream();
      // 获得返回状态码
      int responseCode = conn.getResponseCode();
      // 获得返回信息
      String responseMessage = conn.getResponseMessage();
      // 开发调试:输出信息
      System.out.println("responseCode:" + responseCode + ";\n reponseMessage" + responseMessage);
      if (is != null)
      {
         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
         byte[] buffer = new byte[1024];
         int len = 0;
         while ((len = is.read(buffer)) != -1)
         {
            outStream.write(buffer, 0, len);
         }
         is.close();
         return outStream.toByteArray();
      }
      return null;
   }

   public static String post(String url, String content) throws NoSuchAlgorithmException, KeyManagementException, IOException
   {
      InputStream inputStream = null;
      String response = null;
      // 获得SSL实例
      SSLContext sc = SSLContext.getInstance("SSL");
      // SSL初始化
      sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
      // 创建URL对象
      URL console = new URL(url);
      // url对象强转成HttpsURl对象
      HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
      // 设置SSL socket工厂
      conn.setSSLSocketFactory(sc.getSocketFactory());
      // 设置连接的主机名验证器
      conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
      // 设置连接的请求方法类型
      conn.setRequestMethod(METHOD_POST);
      // 设置连接是否使用缓存
      conn.setUseCaches(false);
      // 设置连接属性(使用UTF-8字符集)
      conn.setRequestProperty("charset", Encoding_UTF8);
      // 设置超时时间
      conn.setConnectTimeout(TIME_OUT);
      // 是否使用这个连接输出?默认为false就是不输出
      conn.setDoOutput(true);
      // 建立连接
      conn.connect();

      DataOutputStream out = new DataOutputStream(conn.getOutputStream());
      out.write(content.getBytes(Encoding_UTF8));
      // 刷新、关闭
      out.flush();
      out.close();

      // 获得返回状态码
      // int responseCode = conn.getResponseCode();
      // 获得返回信息
      // String responseMessage = conn.getResponseMessage();
      // 开发调试:输出信息
      // System.out.println("responseCode:" + responseCode + ";\n
      // reponseMessage:" + responseMessage);
      if (conn.getResponseCode() == HTTP_OK)
      {
         inputStream = conn.getInputStream();
         response = getResponseForBuffer(inputStream);
      } else
      {
         response += conn.getResponseCode() + conn.getResponseMessage();
      }
      // 销毁https连接
      conn.disconnect();
      return response;
   }

   /**
    * 
    * @param url
    * @return
    * @throws NoSuchAlgorithmException
    * @throws KeyManagementException
    * @throws IOException
    */
   public static String get(String url) throws NoSuchAlgorithmException, KeyManagementException, IOException
   {
      InputStream inputStream = null;
      String response = null;
      // 获得SSL实例
      SSLContext sc = SSLContext.getInstance("SSL");
      // SSL初始化
      sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
      // 创建URL对象
      URL console = new URL(url);
      // url对象强转成HttpsURl对象
      HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
      // 设置SSL socket工厂
      conn.setSSLSocketFactory(sc.getSocketFactory());
      // 设置连接的主机名验证器
      conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
      // 设置连接的请求方法类型
      conn.setRequestMethod(METHOD_POST);
      // 设置连接是否使用缓存
      conn.setUseCaches(false);
      // 设置连接属性(使用UTF-8字符集)
      conn.setRequestProperty("charset", Encoding_UTF8);
      // 设置超时时间
      conn.setConnectTimeout(TIME_OUT);
      // 是否使用这个连接输出?默认为false就是不输出
      conn.setDoOutput(true);
      // 建立连接
      conn.connect();

      // DataOutputStream out = new DataOutputStream(conn.getOutputStream());
      // out.write(content.getBytes(Encoding_UTF8));
      // // 刷新、关闭
      // out.flush();
      // out.close();

      if (conn.getResponseCode() == HTTP_OK)
      {
         inputStream = conn.getInputStream();
         response = getResponseForBuffer(inputStream);
      } else
      {
         response += conn.getResponseCode() + conn.getResponseMessage();
      }
      // 销毁https连接
      conn.disconnect();
      return response;
   }

   /**
    * 获得response 返回String
    * 
    * @param inputStream
    * @return String
    */
   private static String getResponseForBuffer(InputStream inputStream)
   {
      BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
      StringBuffer buffer = new StringBuffer();
      String data;
      try
      {
         while ((data = br.readLine()) != null)
         {
            buffer.append(data);
         }
         br.close();
      } catch (IOException e)
      {
         e.printStackTrace();
      }
      return buffer.toString();
   }

}
发布了40 篇原创文章 · 获赞 43 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_37581708/article/details/72367345