java HttpRequest方法

转自 https://blog.csdn.net/ls_man/article/details/78133950

 
  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. try {
  14. URL url = new URL(httpUrl);
  15. HttpURLConnection connection = (HttpURLConnection) url
  16. .openConnection();
  17. connection.setConnectTimeout( 3000); //超时时间,单位毫秒,3000是3秒
  18. connection.setReadTimeout( 3000);
  19. connection.setRequestMethod( "GET");
  20. // 填入apikey到HTTP header(百度接口)
  21. //connection.setRequestProperty("apikey", "11111");
  22. connection.connect();
  23. InputStream is = connection.getInputStream();
  24. reader = new BufferedReader( new InputStreamReader(is, "UTF-8")); //UTF-8
  25. String strRead = null;
  26. while ((strRead = reader.readLine()) != null) {
  27. sbf.append(strRead);
  28. sbf.append( "\r\n");
  29. }
  30. reader.close();
  31. result = sbf.toString();
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. return result;
  36. }