Java调用Http接口(2)--HttpURLConnection调用Http接口
程序员文章站
2023-10-16 13:38:21
HttpURLConnection是JDK自身提供的网络类,不需要引入额外的jar包。文中所使用到的软件版本:Java 1.8.0_191。 1、GET请求 public static void get() { HttpURLConnection connection = null; try { S ......
httpurlconnection是jdk自身提供的网络类,不需要引入额外的jar包。文中所使用到的软件版本:java 1.8.0_191。
1、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(); } }
2、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(); } }
3、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(); } }
4、上传文件及发送键值对数据
4.1、分析数据结构
通过抓包工具分析页面表单上传文件的过程,可以看出传输数据的结构:
4.2、根据分析出的数据结构编写代码
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(); } }
4.3、上传文件方法变通
这种方式上传文件完全是模拟页面的提交行为来编码的,比较繁琐。可以把文件转成字符串,然后通过键值对传给服务端,服务端执行相反的过程来存储文件:
客户端:文件-> 字节数组->base64字符串
服务端:base64字符串-> 字节数组->文件
按照这种方式来实现应该比较容易,这里就不演示了。
5、完整例子
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(); } }