标签:catch tput 执行 art throws null upload sock json
HttpURLConnection是JDK自身提供的网络类,不需要引入额外的jar包。文中所使用到的软件版本:Java 1.8.0_191。
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(); } }
通过抓包工具分析页面表单上传文件的过程,可以看出传输数据的结构:
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("upload返回结果:" + back); } else { System.out.println("upload请求状态码:" + connection.getResponseCode()); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } }
这种方式上传文件完全是模拟页面的提交行为来编码的,比较繁琐。可以把文件转成字符串,然后通过键值对传给服务端,服务端执行相反的过程来存储文件:
客户端:文件-> 字节数组->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("upload返回结果:" + back); } else { System.out.println("upload请求状态码:" + 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(); } }
Java调用Http接口(2)--HttpURLConnection调用Http接口
标签:catch tput 执行 art throws null upload sock json
原文地址:https://www.cnblogs.com/wuyongyin/p/11915587.html