Java模擬POST請求發送二進制數據

在進行程序之間數據通訊時咱們有時候就須要自定義二進制格式,而後經過HTTP進行二進制數據交互。交互的示例代碼以下:java

public static void main(String[] args) { String result = ""; try { String url = "http://localhost:8080/Demo/SiteApi"; URL realUrl = new URL(url); // 打開和URL之間的鏈接
        URLConnection conn = realUrl.openConnection(); // 設置通用的請求屬性
        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", "application/octet-stream"); // 發送POST請求必須設置以下兩行
        conn.setDoOutput(true); conn.setDoInput(true); // 發送請求參數
        DataOutputStream dos=new DataOutputStream(conn.getOutputStream()); String content="I love china"; dos.write(content.getBytes()); // flush輸出流的緩衝
 dos.flush(); // 定義BufferedReader輸入流來讀取URL的響應
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } System.out.println(result);//打印輸出結果
    } catch (Exception e) { System.out.println("異常," + e.getMessage()); e.printStackTrace(); } }

上面是模擬的http請求,若是是https請求,而且咱們本身搭建的https可能證書不合法,所以須要在請求前加上下面的代碼:app

javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { if (arg0.equals("119.84.112.220")) { return true; } return false; } });
相關文章
相關標籤/搜索