当前位置:   article > 正文

java代码使用Get请求或者Post请求获取网络内容_java 发送 get获取网络资源

java 发送 get获取网络资源

引入的依赖包,也可以去 阿里仓库下载   ————>前往阿里云仓库

  1. <dependency>
  2. <groupId>org.apache.commons</groupId>
  3. <artifactId>commons-lang3</artifactId>
  4. <version>3.7</version>
  5. <scope>test</scope>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework</groupId>
  9. <artifactId>spring-context</artifactId>
  10. <version>5.2.1.RELEASE</version>
  11. </dependency>

一个Get Post请求的java代码

  1. import org.apache.commons.lang3.StringUtils;
  2. import org.springframework.util.StreamUtils;
  3. import java.io.*;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. import java.nio.charset.Charset;
  7. import java.util.Map;
  8. public class HttpUtil {
  9. /**
  10. * post请求
  11. * @param urlStr
  12. * @param param
  13. * @param userAgent
  14. * @return
  15. */
  16. public static String httpPost(String urlStr,String param,String userAgent){
  17. try {
  18. URL url = new URL(urlStr);
  19. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  20. conn.setRequestMethod("POST");
  21. conn.setRequestProperty("Content-Type",
  22. "application/x-www-form-urlencoded");
  23. conn.setReadTimeout(5000);
  24. conn.setConnectTimeout(60 * 1000);
  25. if(StringUtils.isNotBlank(userAgent)){
  26. conn.setRequestProperty("User-Agent",
  27. userAgent);
  28. }
  29. conn.setUseCaches(false);
  30. conn.setDoInput(true);
  31. conn.setDoOutput(true);
  32. BufferedOutputStream out = new BufferedOutputStream(conn
  33. .getOutputStream());
  34. BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
  35. bw.write(param);
  36. bw.flush();
  37. bw.close();
  38. if (conn.getResponseCode()==200){
  39. BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
  40. String tempStr = null;
  41. String str = "";
  42. while ((tempStr=br.readLine())!=null){
  43. str +=tempStr;
  44. }
  45. br.close();
  46. return str;
  47. }
  48. }catch (Exception e){
  49. e.printStackTrace();
  50. }
  51. return null;
  52. }
  53. /**
  54. * post请求
  55. * @param urlStr
  56. * @param xmlParam
  57. * @return
  58. */
  59. public static String httpPost(String urlStr,String xmlParam){
  60. return httpPost(urlStr,xmlParam,null);
  61. }
  62. /**
  63. * 调用外部接口,并返回响应结果
  64. * @param httpUrl
  65. * @param params
  66. * @return
  67. * @throws Exception
  68. */
  69. public static String sendHttpPostRequest(String httpUrl, Map<String, String> params) throws Exception{
  70. URL url = new URL(httpUrl);
  71. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  72. conn.setRequestMethod("POST");
  73. conn.setDoOutput(true);
  74. if(params != null && params.size() > 0){
  75. StringBuilder sb = new StringBuilder();
  76. for(Map.Entry<String, String> entry : params.entrySet()){
  77. sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
  78. }
  79. conn.getOutputStream().write(sb.substring(1).getBytes("utf-8"));
  80. }
  81. conn.connect();
  82. String responseContent = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("utf-8"));
  83. conn.disconnect();
  84. return responseContent;
  85. }
  86. public static String sendHttpGetRequest(String httpUrl, Map<String, String> params) throws Exception{
  87. try {
  88. if(params != null && params.size() > 0){
  89. StringBuilder sb = new StringBuilder();
  90. for(Map.Entry<String, String> entry : params.entrySet()){
  91. sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
  92. }
  93. sb = new StringBuilder(sb.substring(1));
  94. if(httpUrl.contains("?")){
  95. httpUrl += "&"+sb.toString();
  96. }else{
  97. httpUrl += "?"+sb.toString();
  98. }
  99. }
  100. URL url = new URL(httpUrl);
  101. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  102. conn.setRequestMethod("GET");
  103. conn.setDoOutput(true);
  104. conn.connect();
  105. String responseContent = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("utf-8"));
  106. conn.disconnect();
  107. return responseContent;
  108. } catch (IOException e) {
  109. e.printStackTrace();
  110. return null;
  111. }
  112. }
  113. //获得网络路径
  114. public static InputStream getImageStream(String url) throws Exception{
  115. HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
  116. connection.setReadTimeout(5000);
  117. connection.setConnectTimeout(5000);
  118. connection.setRequestMethod("GET");
  119. connection.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36");
  120. if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
  121. return connection.getInputStream();
  122. }else{
  123. throw new Exception("响应状态:" + connection.getResponseCode() + "\n" +
  124. "响应内容:" + connection.getResponseMessage());
  125. }
  126. }
  127. //判断当前请求是否有效
  128. public static boolean sendGetRequestAck(String url) throws Exception{
  129. HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
  130. connection.setReadTimeout(5000);
  131. connection.setConnectTimeout(5000);
  132. connection.setRequestMethod("GET");
  133. connection.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36");
  134. if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
  135. return true;
  136. }else{
  137. return false;
  138. }
  139. }
  140. //把字节流转换成字节数组
  141. public static byte[] toByteArray(InputStream input) {
  142. try {
  143. ByteArrayOutputStream output = new ByteArrayOutputStream();
  144. byte[] buffer = new byte[1024*4];
  145. int n = 0;
  146. while (-1 != (n = input.read(buffer))) {
  147. output.write(buffer, 0, n);
  148. }
  149. return output.toByteArray();
  150. } catch (IOException e) {
  151. e.printStackTrace();
  152. return null;
  153. }
  154. }
  155. //把字节数组转换成字节流
  156. public static InputStream toInputStream(byte[] bytes){
  157. return new ByteArrayInputStream(bytes);
  158. }
  159. //字节流转换字节流
  160. public static InputStream toInputStream(InputStream input){
  161. return toInputStream(toByteArray(input));
  162. }
  163. }

 

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

闽ICP备14008679号