https://www.cnblogs.com/jeffen/p/6937788.html
随着网络上java应用越来越多,场景越来越复杂,所以应用之间经常通过HTTP接口来访问资源
首先了解了URL的最常用的两种请求方式:第一种GET,第二种POST
GET:get请求可以获取页面,也可以把参数放到URL后面以?分割传递数据,参数之间以&关联,例如 :8086/sp-test/usertest/1.0/query?mobile=15334567890&name=zhansan
POST:post请求的参数是放在HTTP请求的正文里,请求的参数被封装起来通过流的方式传递
1.HttpURLConnection
1.1简介:
在java.net包中,已经提供访问HTTP协议的基本功能类:HttpURLConnection,可以向其他系统发送GET,POST访问请求
1.2 GET方式调用
1 private void httpURLGETCase() { 2 String methodUrl = "http://110.32.44.11:8086/sp-test/usertest/1.0/query"; 3 HttpURLConnection connection = null; 4 BufferedReader reader = null; 5 String line = null; 6 try { 7 URL url = new URL(methodUrl + "?mobile=15334567890&name=zhansan"); 8 connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection 9 connection.setRequestMethod("GET");// 默认GET请求 10 connection.connect();// 建立TCP连接 11 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 12 reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求 13 StringBuilder result = new StringBuilder(); 14 // 循环读取流 15 while ((line = reader.readLine()) != null) { 16 result.append(line).append(System.getProperty("line.separator"));// "\n" 17 } 18 System.out.println(result.toString()); 19 } 20 } catch (IOException e) { 21 e.printStackTrace(); 22 } finally { 23 try { 24 reader.close(); 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 connection.disconnect(); 29 } 30 }