HTTP.java 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package edu.nju.util;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import edu.nju.service.RecommendService;
  5. import org.json.JSONException;
  6. import java.io.*;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. import java.net.URLConnection;
  10. import java.nio.charset.Charset;
  11. import java.util.List;
  12. import java.util.Map;
  13. import org.apache.commons.io.IOUtils;
  14. import org.slf4j.Logger;
  15. import org.slf4j.LoggerFactory;
  16. public class HTTP {
  17. static Logger logger= LoggerFactory.getLogger(RecommendService.class);
  18. /**
  19. * 向指定URL发送GET方法的请求
  20. *
  21. * @param url
  22. * 发送请求的URL
  23. * @param param
  24. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  25. * @return URL 所代表远程资源的响应结果
  26. */
  27. public static String sendGet(String url, String param) {
  28. StringBuilder result = new StringBuilder();
  29. BufferedReader in = null;
  30. try {
  31. String urlNameString = url + "?" + param;
  32. URL realUrl = new URL(urlNameString);
  33. // 打开和URL之间的连接
  34. URLConnection connection = realUrl.openConnection();
  35. // 设置通用的请求属性
  36. connection.setRequestProperty("accept", "*/*");
  37. // connection.setRequestProperty("connection", "Keep-Alive");
  38. connection.setRequestProperty("user-agent",
  39. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  40. // 建立实际的连接
  41. connection.connect();
  42. // 获取所有响应头字段
  43. // Map<String, List<String>> map = connection.getHeaderFields();
  44. // 遍历所有的响应头字段
  45. // for (String key : map.keySet()) {
  46. // System.out.println(key + "--->" + map.get(key));
  47. // }
  48. // 定义 BufferedReader输入流来读取URL的响应
  49. in = new BufferedReader(new InputStreamReader(
  50. connection.getInputStream()));
  51. String line;
  52. while ((line = in.readLine()) != null) {
  53. result.append(line);
  54. }
  55. } catch (Exception e) {
  56. System.out.println("发送GET请求出现异常!" + e);
  57. e.printStackTrace();
  58. }
  59. // 使用finally块来关闭输入流
  60. finally {
  61. try {
  62. if (in != null) {
  63. in.close();
  64. }
  65. } catch (Exception e2) {
  66. e2.printStackTrace();
  67. }
  68. }
  69. return result.toString();
  70. }
  71. /**
  72. * 从输入流中获取字节数组
  73. * @param inputStream
  74. * @return
  75. * @throws IOException
  76. */
  77. public static byte[] readInputStream(InputStream inputStream) throws IOException {
  78. byte[] buffer = new byte[1024];
  79. int len = 0;
  80. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  81. while((len = inputStream.read(buffer)) != -1) {
  82. bos.write(buffer, 0, len);
  83. }
  84. bos.close();
  85. return bos.toByteArray();
  86. }
  87. /**
  88. * 从网络Url中下载文件
  89. * @param urlStr
  90. * @param fileName
  91. * @param savePath
  92. * @throws IOException
  93. */
  94. public static void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException{
  95. URL url = new URL(urlStr);
  96. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  97. //设置超时间为3秒
  98. conn.setConnectTimeout(3 * 1000);
  99. //防止屏蔽程序抓取而返回403错误
  100. conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  101. conn.setRequestProperty("Charset", "UTF-8");
  102. //得到输入流
  103. InputStream inputStream = conn.getInputStream();
  104. //获取自己数组
  105. byte[] getData = readInputStream(inputStream);
  106. //文件保存位置
  107. File saveDir = new File(savePath);
  108. if(!saveDir.exists()){ saveDir.mkdir(); }
  109. File file = new File(saveDir + File.separator + fileName);
  110. FileOutputStream fos = new FileOutputStream(file);
  111. fos.write(getData);
  112. if(fos != null) { fos.close(); }
  113. if(inputStream != null) { inputStream.close(); }
  114. System.out.println("info:" + url + " download success");
  115. }
  116. public static String readStringFromUrl(String url) throws IOException, JSONException {
  117. InputStream is = new URL(url).openStream();
  118. try {
  119. BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
  120. String jsonText = readAll(rd);
  121. return jsonText;
  122. } finally {
  123. is.close();
  124. }
  125. }
  126. private static String readAll(Reader rd) throws IOException {
  127. StringBuilder sb = new StringBuilder();
  128. int cp;
  129. while ((cp = rd.read()) != -1) {
  130. sb.append((char) cp);
  131. }
  132. return sb.toString();
  133. }
  134. public static boolean sendPut(String host, String url, String param) {
  135. try {
  136. String urlNameString = url + "?" + param;
  137. logger.info(urlNameString);
  138. URL realUrl = new URL(urlNameString);
  139. // 打开和URL之间的连接
  140. HttpURLConnection connection;
  141. connection = (HttpURLConnection)realUrl.openConnection();
  142. connection.setDoInput(true);
  143. connection.setDoOutput(true);
  144. // 设置通用的请求属性
  145. connection.setRequestProperty("accept", "*/*");
  146. connection.setRequestProperty("Host", host);
  147. connection.setRequestMethod("PUT");
  148. // connection.setRequestProperty("connection", "Keep-Alive");
  149. connection.setRequestProperty("user-agent",
  150. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  151. // 建立实际的连接
  152. connection.connect();
  153. // 获取所有响应头字段
  154. Map<String, List<String>> map = connection.getHeaderFields();
  155. for (String key : map.keySet()) {
  156. System.out.println(key + "--->" + map.get(key));
  157. }
  158. return true;
  159. } catch (Exception e) {
  160. logger.info("发送put出错");
  161. System.out.println("发送PUT请求出现异常!" + e);
  162. e.printStackTrace();
  163. return false;
  164. }
  165. }
  166. public static String postBody(String urlPath, String json) throws Exception {
  167. PrintWriter out = null;
  168. BufferedReader in = null;
  169. String result = "";
  170. try {
  171. URL realUrl = new URL(urlPath);
  172. // 打开和URL之间的连接
  173. HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
  174. // 设置通用的请求属性
  175. conn.setRequestMethod("POST");
  176. // 发送POST请求必须设置下面的属性
  177. conn.setDoOutput(true);
  178. conn.setDoInput(true);
  179. conn.setUseCaches(false);
  180. //设置请求属性
  181. conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
  182. conn.connect();
  183. // 获取URLConnection对象对应的输出流
  184. out = new PrintWriter(conn.getOutputStream());
  185. // 发送请求参数
  186. out.print(json);
  187. // flush输出流的缓冲
  188. out.flush();
  189. // 定义BufferedReader输入流来读取URL的响应
  190. in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  191. String line = "";
  192. while ((line = in.readLine()) != null) {
  193. result += line;
  194. }
  195. } catch (Exception e) {
  196. throw new RuntimeException("远程通路异常"+e.toString());
  197. }
  198. // 使用finally块来关闭输出流、输入流
  199. finally {
  200. try {
  201. if (out != null) {
  202. out.close();
  203. }
  204. if (in != null) {
  205. in.close();
  206. }
  207. } catch (IOException ex) {
  208. ex.printStackTrace();
  209. }
  210. }
  211. return result;
  212. }
  213. }