当前位置:   article > 正文

Java调用Rest请求_java rest 请求

java rest 请求
  1. package com.db;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.util.List;
  8. public class RestUtil {
  9. /**
  10. * 实现对REST服务的请求
  11. * @param urlStr
  12. * @param urlParam
  13. * @return
  14. * @throws java.io.IOException
  15. */
  16. public static String httpGet(String urlStr, List<String> urlParam) throws IOException{
  17. if (!urlParam.isEmpty()) {
  18. urlStr += "?";
  19. // 定义一个迭代器,并将MAP值的集合赋值
  20. for (String string : urlParam) {
  21. urlStr += string + "&";
  22. }
  23. urlStr = urlStr.substring(0, urlStr.length() - 1);
  24. }
  25. // 实例一个URL资源
  26. URL url = new URL(urlStr);
  27. //实例一个HTTP CONNECT
  28. HttpURLConnection connet = (HttpURLConnection) url.openConnection();
  29. connet.setRequestMethod("GET");
  30. connet.setRequestProperty("Charset", "UTF-8");
  31. connet.setRequestProperty("Content-Type", "application/json");
  32. connet.setConnectTimeout(15000);// 连接超时 单位毫秒
  33. connet.setReadTimeout(15000);// 读取超时 单位毫秒
  34. if(connet.getResponseCode() != 200){
  35. System.out.println("请求异常" + urlStr);
  36. return "";
  37. }
  38. //将返回的值存入到String中
  39. BufferedReader brd = new BufferedReader(new InputStreamReader(connet.getInputStream(),"UTF-8"));
  40. StringBuilder sb = new StringBuilder();
  41. String line;
  42. while((line = brd.readLine()) != null){
  43. sb.append(line);
  44. }
  45. brd.close();
  46. connet.disconnect();
  47. return sb.toString();
  48. }
  49. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/302782
推荐阅读
相关标签
  

闽ICP备14008679号