7d2006109715f47a792a7d1276e0482fc7a31989.svn-base 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package com.yihu.utils;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.PrintWriter;
  8. import java.net.URL;
  9. import java.net.URLConnection;
  10. import java.util.List;
  11. import java.util.Map;
  12. import javax.script.ScriptEngine;
  13. import javax.script.ScriptEngineManager;
  14. import org.apache.commons.httpclient.HttpClient;
  15. import org.apache.commons.httpclient.HttpException;
  16. import org.apache.commons.httpclient.methods.PostMethod;
  17. import org.apache.commons.httpclient.methods.multipart.FilePart;
  18. import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
  19. import org.apache.commons.httpclient.methods.multipart.Part;
  20. public class HttpGetClient {
  21. /**
  22. * 向指定URL发送GET方法的请求
  23. *
  24. * @param url
  25. * 发送请求的URL
  26. * @param param
  27. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  28. * @return URL 所代表远程资源的响应结果
  29. */
  30. public static String sendGet(String url, String param) {
  31. String result = "";
  32. BufferedReader in = null;
  33. try {
  34. String urlNameString = url + "?" + param;
  35. URL realUrl = new URL(urlNameString);
  36. // 打开和URL之间的连接
  37. URLConnection connection = realUrl.openConnection();
  38. // 设置通用的请求属性
  39. connection.setRequestProperty("accept", "*/*");
  40. connection.setRequestProperty("connection", "Keep-Alive");
  41. connection.setRequestProperty("user-agent",
  42. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  43. // 建立实际的连接
  44. connection.connect();
  45. // 获取所有响应头字段
  46. Map<String, List<String>> map = connection.getHeaderFields();
  47. // // 遍历所有的响应头字段
  48. // for (String key : map.keySet()) {
  49. // System.out.println(key + "--->" + map.get(key));
  50. // }
  51. // 定义 BufferedReader输入流来读取URL的响应
  52. in = new BufferedReader(new InputStreamReader(
  53. connection.getInputStream()));
  54. String line;
  55. while ((line = in.readLine()) != null) {
  56. result += line;
  57. }
  58. } catch (Exception e) {
  59. System.out.println("发送GET请求出现异常!" + e);
  60. e.printStackTrace();
  61. }
  62. // 使用finally块来关闭输入流
  63. finally {
  64. try {
  65. if (in != null) {
  66. in.close();
  67. }
  68. } catch (Exception e2) {
  69. e2.printStackTrace();
  70. }
  71. }
  72. // byte[] t_utf8 = testStr.getBytes("UTF-8");
  73. // String ut_utf8 = new String(t_utf8, "UTF-8");
  74. return result;
  75. }
  76. }