Java_HttpRequest方法

  1. /**

  2. * http调用

  3. *

  4. * @param httpUrl :请求接口

  5. * @param httpArg :参数

  6. * @return 返回结果

  7. */

  8. public static String httpRequest(String httpUrl, String httpArg) {

  9. BufferedReader reader = null;

  10. String result = null;

  11. StringBuffer sbf = new StringBuffer();

  12. httpUrl = httpUrl + "?" + httpArg;

  13.  
  14. try {

  15. URL url = new URL(httpUrl);

  16. HttpURLConnection connection = (HttpURLConnection) url

  17. .openConnection();

  18. connection.setConnectTimeout(3000);//超时时间,单位毫秒,3000是3秒

  19. connection.setReadTimeout(3000);

  20. connection.setRequestMethod("GET");

  21. // 填入apikey到HTTP header(百度接口)

  22. //connection.setRequestProperty("apikey", "11111");

  23. connection.connect();

  24. InputStream is = connection.getInputStream();

  25. reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));//UTF-8

  26. String strRead = null;

  27. while ((strRead = reader.readLine()) != null) {

  28. sbf.append(strRead);

  29. sbf.append("\r\n");

  30. }

  31. reader.close();

  32. result = sbf.toString();

  33. } catch (Exception e) {

  34. e.printStackTrace();

  35. }

  36. return result;

  37. }

猜你喜欢

转载自blog.csdn.net/weixin_41508948/article/details/81707933