Java 模拟http请求

时间:2023-03-09 05:14:03
Java 模拟http请求
  1. package ln;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.PrintWriter;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. /**
  10. * 用于模拟HTTP请求中GET/POST方式
  11. * @author landa
  12. *
  13. */
  14. public class HttpUtils {
  15. /**
  16. * 发送GET请求
  17. *
  18. * @param url
  19. *            目的地址
  20. * @param parameters
  21. *            请求参数,Map类型。
  22. * @return 远程响应结果
  23. */
  24. public static String sendGet(String url, Map<String, String> parameters) {
  25. String result="";
  26. BufferedReader in = null;// 读取响应输入流
  27. StringBuffer sb = new StringBuffer();// 存储参数
  28. String params = "";// 编码之后的参数
  29. try {
  30. // 编码请求参数
  31. if(parameters.size()==1){
  32. for(String name:parameters.keySet()){
  33. sb.append(name).append("=").append(
  34. java.net.URLEncoder.encode(parameters.get(name),
  35. "UTF-8"));
  36. }
  37. params=sb.toString();
  38. }else{
  39. for (String name : parameters.keySet()) {
  40. sb.append(name).append("=").append(
  41. java.net.URLEncoder.encode(parameters.get(name),
  42. "UTF-8")).append("&");
  43. }
  44. String temp_params = sb.toString();
  45. params = temp_params.substring(0, temp_params.length() - 1);
  46. }
  47. String full_url = url + "?" + params;
  48. System.out.println(full_url);
  49. // 创建URL对象
  50. java.net.URL connURL = new java.net.URL(full_url);
  51. // 打开URL连接
  52. java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL
  53. .openConnection();
  54. // 设置通用属性
  55. httpConn.setRequestProperty("Accept", "*/*");
  56. httpConn.setRequestProperty("Connection", "Keep-Alive");
  57. httpConn.setRequestProperty("User-Agent",
  58. "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
  59. // 建立实际的连接
  60. httpConn.connect();
  61. // 响应头部获取
  62. Map<String, List<String>> headers = httpConn.getHeaderFields();
  63. // 遍历所有的响应头字段
  64. for (String key : headers.keySet()) {
  65. System.out.println(key + "\t:\t" + headers.get(key));
  66. }
  67. // 定义BufferedReader输入流来读取URL的响应,并设置编码方式
  68. in = new BufferedReader(new InputStreamReader(httpConn
  69. .getInputStream(), "UTF-8"));
  70. String line;
  71. // 读取返回的内容
  72. while ((line = in.readLine()) != null) {
  73. result += line;
  74. }
  75. } catch (Exception e) {
  76. e.printStackTrace();
  77. }finally{
  78. try {
  79. if (in != null) {
  80. in.close();
  81. }
  82. } catch (IOException ex) {
  83. ex.printStackTrace();
  84. }
  85. }
  86. return result ;
  87. }
  88. /**
  89. * 发送POST请求
  90. *
  91. * @param url
  92. *            目的地址
  93. * @param parameters
  94. *            请求参数,Map类型。
  95. * @return 远程响应结果
  96. */
  97. public static String sendPost(String url, Map<String, String> parameters) {
  98. String result = "";// 返回的结果
  99. BufferedReader in = null;// 读取响应输入流
  100. PrintWriter out = null;
  101. StringBuffer sb = new StringBuffer();// 处理请求参数
  102. String params = "";// 编码之后的参数
  103. try {
  104. // 编码请求参数
  105. if (parameters.size() == 1) {
  106. for (String name : parameters.keySet()) {
  107. sb.append(name).append("=").append(
  108. java.net.URLEncoder.encode(parameters.get(name),
  109. "UTF-8"));
  110. }
  111. params = sb.toString();
  112. } else {
  113. for (String name : parameters.keySet()) {
  114. sb.append(name).append("=").append(
  115. java.net.URLEncoder.encode(parameters.get(name),
  116. "UTF-8")).append("&");
  117. }
  118. String temp_params = sb.toString();
  119. params = temp_params.substring(0, temp_params.length() - 1);
  120. }
  121. // 创建URL对象
  122. java.net.URL connURL = new java.net.URL(url);
  123. // 打开URL连接
  124. java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL
  125. .openConnection();
  126. // 设置通用属性
  127. httpConn.setRequestProperty("Accept", "*/*");
  128. httpConn.setRequestProperty("Connection", "Keep-Alive");
  129. httpConn.setRequestProperty("User-Agent",
  130. "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
  131. // 设置POST方式
  132. httpConn.setDoInput(true);
  133. httpConn.setDoOutput(true);
  134. // 获取HttpURLConnection对象对应的输出流
  135. out = new PrintWriter(httpConn.getOutputStream());
  136. // 发送请求参数
  137. out.write(params);
  138. // flush输出流的缓冲
  139. out.flush();
  140. // 定义BufferedReader输入流来读取URL的响应,设置编码方式
  141. in = new BufferedReader(new InputStreamReader(httpConn
  142. .getInputStream(), "UTF-8"));
  143. String line;
  144. // 读取返回的内容
  145. while ((line = in.readLine()) != null) {
  146. result += line;
  147. }
  148. } catch (Exception e) {
  149. e.printStackTrace();
  150. } finally {
  151. try {
  152. if (out != null) {
  153. out.close();
  154. }
  155. if (in != null) {
  156. in.close();
  157. }
  158. } catch (IOException ex) {
  159. ex.printStackTrace();
  160. }
  161. }
  162. return result;
  163. }
  164. /**
  165. * 主函数,测试请求
  166. *
  167. * @param args
  168. */
  169. public static void main(String[] args) {
  170. Map<String, String> parameters = new HashMap<String, String>();
  171. parameters.put("name", "sarin");
  172. String result =sendGet("http://www.baidu.com", parameters);
  173. System.out.println(result);
  174. }
  175. }