Java HttpURLConnection POST方式调用接口并携带参数

package testi;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.URL;
import java.net.URLEncoder;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

public class HttpsHelper {
	public static void main(String args[]) throws Exception {
		//System.out.println(args[0]); // 打印 Hello World 
		if(args.length != 3) {
			System.out.println("参数错误,0-postStr,1-url,2-方式:post或get");
			return;
		}
		else {
			if(args[2] == "post")
				new HttpsHelper().SendPostHttp(args[0], args[1]);
			else
				new HttpsHelper().SendGetHttp(args[0], args[1]);
		}
		
	  }

	  public void SendPostHttp(String postJsonStr, String url) throws Exception {
	    
	    String postData = postJsonStr;//getJson();
	    HttpsURLConnection conn = null;
	    //String param="name="+URLEncoder.encode("丁丁","UTF-8");
	    OutputStream out = null;
	    String rsp = null;
	    byte[] byteArray = postData.getBytes("utf-8");
	    try {
	      URL uri = new URL(url);
	      conn = (HttpsURLConnection) uri.openConnection();
	      //忽略证书验证--Begin
	      conn.setHostnameVerifier(new My_TrustAnyHostnameVerifier());
	      //忽略证书验证--End
	      conn.setRequestMethod("POST");
	      conn.setDoInput(true);
	      conn.setDoOutput(true);
	      conn.setRequestProperty("Host", uri.getHost());
	      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	      out = conn.getOutputStream();
	      out.write(byteArray);
	      out.close();
	      if(conn.getResponseCode()==200) {
	        rsp = getStreamAsString(conn.getInputStream(), "utf-8");
	      }else {
	        rsp = getStreamAsString(conn.getErrorStream(), "utf-8");
	      }
	      
	      System.out.println(rsp);

	    } catch (Exception e) {
	      if(null!=out)
	        out.close();
	      e.printStackTrace();
	      
	    }
	    
	  }
	  
	  public void SendGetHttp(String postJsonStr, String url) throws Exception {
		  	String postData = postJsonStr;//getJson();
		    HttpsURLConnection conn = null;
		    url = url + "?" + postData;
		    //OutputStream out = null;
		    String rsp = null;
		    //byte[] byteArray = postData.getBytes("utf-8");
		    try {
		      URL uri = new URL(url);
		      conn = (HttpsURLConnection) uri.openConnection();
		      //忽略证书验证--Begin
		      conn.setHostnameVerifier(new My_TrustAnyHostnameVerifier());
		      //忽略证书验证--End
		      conn.setRequestMethod("GET");
		      conn.setDoInput(true);
		      conn.setDoOutput(true);
		      conn.setRequestProperty("Host", uri.getHost());
		      conn.setRequestProperty("Content-Type", "text/html; charset=UTF-8");
		      //out = conn.getOutputStream();
		      ///out.write(byteArray);
		      //out.close();
		      if(conn.getResponseCode()==200) {
		        rsp = getStreamAsString(conn.getInputStream(), "utf-8");
		      }else {
		        rsp = getStreamAsString(conn.getErrorStream(), "utf-8");
		      }
		      
		      System.out.println(rsp);

		    } catch (Exception e) {
		      //if(null!=out)
		        //out.close();
		      e.printStackTrace();
		      
		    }
		}
	  
	  /**
	   * getJson
	   * 
	   */
	  private static String getJson() {
	    return "{" + "\"name\"" + ":" + "\"hello\"" + "}";
	  }
	 

	  private static String getStreamAsString(InputStream stream, String charset) throws IOException {
	    try {
	      Reader reader = new InputStreamReader(stream, charset);
	      StringBuilder response = new StringBuilder();

	      final char[] buff = new char[1024];
	      int read = 0;
	      while ((read = reader.read(buff)) > 0) {
	        response.append(buff, 0, read);
	      }

	      return response.toString();
	    } finally {
	      if (stream != null) {
	        stream.close();
	      }
	    }
	  }

	}

	//定制Verifier
	class My_TrustAnyHostnameVerifier implements HostnameVerifier {
	  public boolean verify(String hostname, SSLSession session) {
	    return true;
	  }

}

参考:

http://www.manongjc.com/detail/18-hgdiiupleyulnbu.html

https://www.jb51.net/article/73621.htm
https://blog.csdn.net/u011400521/article/details/78251857
https://www.jb51.net/article/168581.htm

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注