URL编程

URL类

  1. URL:统一资源定位符,它表示Internet上某一资源的地址
    1. URL url = new URL("url");
    2. HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
    3. InputStream inputStream = httpURLConnection.getInputStream();

调用http

get

  1. String methodUrl = "http://110.32.44.11:8086/sp-test/usertest/1.0/query";
  2. HttpURLConnection connection = null;
  3. BufferedReader reader = null;
  4. String line = null;
  5. try {
  6. URL url = new URL(methodUrl + "?mobile=15334567890&name=zhansan");
  7. connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
  8. connection.setRequestMethod("GET");// 默认GET请求
  9. connection.connect();// 建立TCP连接
  10. if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
  11. reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
  12. StringBuilder result = new StringBuilder();
  13. // 循环读取流
  14. while ((line = reader.readLine()) != null) {
  15. result.append(line).append(System.getProperty("line.separator"));// "\n"
  16. }
  17. System.out.println(result.toString());
  18. }
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. } finally {
  22. try {
  23. reader.close();
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. connection.disconnect();
  28. }
  29. }

post

HttpClient方式调用

Spring RestTemplate方式调用