Java调用Http/Https接口(2)--HttpURLConnection/HttpsURLConnection调用Http/Https接口

HttpURLConnection是JDK自身提供的网络类,不需要引入额外的jar包。文中所使用到的软件版本:Java 1.8.0_191。

1、服务端

参见Java调用Http接口(1)--编写服务端 

2、调用Http接口 2.1、GET请求

public static void get() { try { String requestPath = "http://localhost:8080/demo/httptest/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); HttpURLConnection 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(); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgzpyw.html