HttpURLConnection是JDK自身提供的網絡類,不須要引入額外的jar包。文中所使用到的軟件版本:Java 1.8.0_191。java
public static void get() { HttpURLConnection connection = null; try { String requestPath = "http://localhost:8080/webframe/demo/test/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8"); URL url = new URL(requestPath); //設置代理 //InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 8888); //Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); //connection = (HttpURLConnection)url.openConnection(proxy); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { byte[] b = getBytesFromInputStream(connection.getInputStream()); String back = new String(b); System.out.println("GET返回結果:" + back); } else { System.out.println("GET請求狀態碼:" + connection.getResponseCode()); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } }
public static void post() { HttpURLConnection connection = null; try { String requestPath = "http://localhost:8080/webframe/demo/test/getUser"; URL url = new URL(requestPath); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.connect(); String param = "userId=1000&userName=李白"; setBytesToOutputStream(connection.getOutputStream(), param.getBytes()); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { byte[] b = getBytesFromInputStream(connection.getInputStream()); String back = new String(b); System.out.println("POST返回結果:" + back); } else { System.out.println("POST返回狀態碼:" + connection.getResponseCode()); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } }
public static void post2() { HttpURLConnection connection = null; try { String requestPath = "http://localhost:8080/webframe/demo/test/addUser"; URL url = new URL(requestPath); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-type", "application/json"); connection.connect(); String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}"; setBytesToOutputStream(connection.getOutputStream(), param.getBytes()); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { byte[] b = getBytesFromInputStream(connection.getInputStream()); String back = new String(b); System.out.println("POST2返回結果:" + back); } else { System.out.println("POST2返回狀態碼:" + connection.getResponseCode()); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } }
經過抓包工具分析頁面表單上傳文件的過程,能夠看出傳輸數據的結構:web
public static void multi() { String BOUNDARY = java.util.UUID.randomUUID().toString(); String TWO_HYPHENS = "--"; String LINE_END = "\r\n"; HttpURLConnection connection = null; try { String requestPath = "http://localhost:8080/webframe/demo/test/multi"; URL url = new URL(requestPath); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-type", "multipart/form-data; BOUNDARY=" + BOUNDARY); connection.connect(); StringBuffer sb = new StringBuffer(); //封裝鍵值對數據1 sb.append(TWO_HYPHENS).append(BOUNDARY).append(LINE_END); sb.append("Content-Disposition: form-data; name=\"param1\"").append(LINE_END); sb.append(LINE_END); sb.append("參數1").append(LINE_END); //封裝鍵值對數據2 sb.append(TWO_HYPHENS).append(BOUNDARY).append(LINE_END); sb.append("Content-Disposition: form-data; name=\"param2\"").append(LINE_END); sb.append(LINE_END); sb.append("參數2").append(LINE_END); //封裝文件數據 sb.append(TWO_HYPHENS).append(BOUNDARY).append(LINE_END); sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"a.jpg\"").append(LINE_END); sb.append("Content-Type: file/*").append(LINE_END); sb.append(LINE_END); setBytesToOutputStream(connection.getOutputStream(), sb.toString().getBytes()); FileInputStream fileInputStream = new FileInputStream("d:/a.jpg"); setBytesToOutputStream(connection.getOutputStream(), fileInputStream); //寫入標記結束位 byte[] endData = (LINE_END + TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + LINE_END).getBytes(); setBytesToOutputStream(connection.getOutputStream(), endData); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { byte[] b = getBytesFromInputStream(connection.getInputStream()); String back = new String(b); System.out.println("multi返回結果:" + back); } else { System.out.println("multi返回狀態碼:" + connection.getResponseCode()); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } }
這種方式上傳文件徹底是模擬頁面的提交行爲來編碼的,比較繁瑣。能夠把文件轉成字符串,而後經過鍵值對傳給服務端,服務端執行相反的過程來存儲文件:json
客戶端:文件-> 字節數組->Base64字符串數組
服務端:Base64字符串-> 字節數組->文件網絡
按照這種方式來實現應該比較容易,這裏就不演示了。數據結構
package com.inspur.http; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; import java.net.URLEncoder; /** * * 經過HttpURLConnection調用Http接口 * */ public class HttpURLConnectionCase { /** * GET請求 */ public static void get() { HttpURLConnection connection = null; try { String requestPath = "http://localhost:8080/webframe/demo/test/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8"); URL url = new URL(requestPath); //設置代理 //InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 8888); //Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); //connection = (HttpURLConnection)url.openConnection(proxy); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { byte[] b = getBytesFromInputStream(connection.getInputStream()); String back = new String(b); System.out.println("GET返回結果:" + back); } else { System.out.println("GET請求狀態碼:" + connection.getResponseCode()); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } } /** * POST請求,發送鍵值對數據 */ public static void post() { HttpURLConnection connection = null; try { String requestPath = "http://localhost:8080/webframe/demo/test/getUser"; URL url = new URL(requestPath); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.connect(); String param = "userId=1000&userName=李白"; setBytesToOutputStream(connection.getOutputStream(), param.getBytes()); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { byte[] b = getBytesFromInputStream(connection.getInputStream()); String back = new String(b); System.out.println("POST返回結果:" + back); } else { System.out.println("POST返回狀態碼:" + connection.getResponseCode()); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } } /** * POST請求,發送json格式數據 */ public static void post2() { HttpURLConnection connection = null; try { String requestPath = "http://localhost:8080/webframe/demo/test/addUser"; URL url = new URL(requestPath); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty("Content-type", "application/json"); connection.connect(); String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}"; setBytesToOutputStream(connection.getOutputStream(), param.getBytes()); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { byte[] b = getBytesFromInputStream(connection.getInputStream()); String back = new String(b); System.out.println("POST2返回結果:" + back); } else { System.out.println("POST2返回狀態碼:" + connection.getResponseCode()); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } } /** * 上傳文件及發送鍵值對數據 */ public static void multi() { String BOUNDARY = java.util.UUID.randomUUID().toString(); String TWO_HYPHENS = "--"; String LINE_END = "\r\n"; HttpURLConnection connection = null; try { String requestPath = "http://localhost:8080/webframe/demo/test/multi"; URL url = new URL(requestPath); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-type", "multipart/form-data; BOUNDARY=" + BOUNDARY); connection.connect(); StringBuffer sb = new StringBuffer(); //封裝鍵值對數據1 sb.append(TWO_HYPHENS).append(BOUNDARY).append(LINE_END); sb.append("Content-Disposition: form-data; name=\"param1\"").append(LINE_END); sb.append(LINE_END); sb.append("參數1").append(LINE_END); //封裝鍵值對數據2 sb.append(TWO_HYPHENS).append(BOUNDARY).append(LINE_END); sb.append("Content-Disposition: form-data; name=\"param2\"").append(LINE_END); sb.append(LINE_END); sb.append("參數2").append(LINE_END); //封裝文件數據 sb.append(TWO_HYPHENS).append(BOUNDARY).append(LINE_END); sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"a.jpg\"").append(LINE_END); sb.append("Content-Type: file/*").append(LINE_END); sb.append(LINE_END); setBytesToOutputStream(connection.getOutputStream(), sb.toString().getBytes()); FileInputStream fileInputStream = new FileInputStream("d:/a.jpg"); setBytesToOutputStream(connection.getOutputStream(), fileInputStream); //寫入標記結束位 byte[] endData = (LINE_END + TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + LINE_END).getBytes(); setBytesToOutputStream(connection.getOutputStream(), endData); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { byte[] b = getBytesFromInputStream(connection.getInputStream()); String back = new String(b); System.out.println("multi返回結果:" + back); } else { System.out.println("multi返回狀態碼:" + connection.getResponseCode()); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } } /** * 從輸入流獲取數據 * @param in * @return * @throws IOException */ private static byte[] getBytesFromInputStream(InputStream in) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int len; while ((len = in.read(b)) != -1) { baos.write(b, 0, len); } byte[] bytes = baos.toByteArray(); baos.close(); in.close(); return bytes; } /** * 向輸入流發送數據 * @param out * @param bytes * @throws IOException */ private static void setBytesToOutputStream(OutputStream out, byte[] bytes) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); byte[] b = new byte[1024]; int len; while ((len = bais.read(b)) != -1) { out.write(b, 0, len); } out.flush(); } /** * 向輸入流發送數據 * @param out * @param bytes * @throws IOException */ private static void setBytesToOutputStream(OutputStream out, InputStream data) throws IOException { byte[] b = new byte[1024]; int len; while ((len = data.read(b)) != -1) { out.write(b, 0, len); } out.flush(); } public static void main(String[] args) { get(); post(); post2(); multi(); } }