get/post方式调用http接口 (二)

2014-11-24 07:23:19 · 作者: · 浏览: 1
ram param1
33 * @param param2
34 * @return
35 */
36 public static String getHttp(String param1,String param2){
37 String responseMsg = "";
38
39 // 1.构造HttpClient的实例
40 HttpClient httpClient = new HttpClient();
41
42 // 用于测试的http接口的url
43 String url="http://localhost:8080/UpDown/httpServer param1="+param1+"¶m2="+param2;
44
45 // 2.创建GetMethod的实例
46 GetMethod getMethod = new GetMethod(url);
47
48 // 使用系统系统的默认的恢复策略
49 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
50 new DefaultHttpMethodRetryHandler());
51
52 try {
53 //3.执行getMethod,调用http接口
54 httpClient.executeMethod(getMethod);
55
56 //4.读取内容
57 byte[] responseBody = getMethod.getResponseBody();
58
59 //5.处理返回的内容
60 responseMsg = new String(responseBody);
61 log.info(responseMsg);
62
63 } catch (HttpException e) {
64 e.printStackTrace();
65 } catch (IOException e) {
66 e.printStackTrace();
67 }finally{
68 //6.释放连接
69 getMethod.releaseConnection();
70 }
71 return responseMsg;
72 }
73
74 /**
75 * post方式
76 * @param param1
77 * @param param2
78 * @return
79 */
80 public static String postHttp(String param1,String param2) {
81 String responseMsg = "";
82
83 //1.构造HttpClient的实例
84 HttpClient httpClient=new HttpClient();
85
86 httpClient.getParams().setContentCharset("GBK");
87
88 String url="http://localhost:8080/UpDown/httpServer";
89
90 //2.构造PostMethod的实例
91 PostMethod postMethod=new PostMethod(url);
92
93 //3.把参数值放入到PostMethod对象中
94 //方式1:
95 /* Nameva luePair[] data = { new Nameva luePair("param1", param1),
96 new Nameva luePair("param2", param2) };
97 postMethod.setRequestBody(data);*/
98
99 //方式2:
100 postMethod.addParameter("param1", param1);
101 postMethod.addParameter("param2", param2);
102
103
104 try {
105 // 4.执行postMethod,调用http接口
106 httpClient.executeMethod(postMethod);//200
107
108 //5.读取内容
109 responseMsg = postMethod.getResponseBodyAsString().trim();
110 log.info(responseMsg);
111
112 //6.处理返回的内容
113
114 } catch (HttpException e) {
115 e.printStackTrace();
116 } catch (IOException e) {
117 e.printStackTrace();
118 } finally {
119 //7.释放连接
120 postMethod.releaseConnection();
121 }
122 return responseMsg;
123 }
124
125 /**
126 * 测试的main方法
127 * @param args
128 */
129 public static void main(String[] args) {
130
131 String param1="111";
132 String param2="222";
133 //get
134 // System.out.println("get方式调用http接口\n"+getHttp(param1, param2));
135
136 //post
137 System.out.println("post方式调用http接口\n"+postHttp(param1,param2));
138 }
139 }


result
在HttpClientUtil运行main方法,分别运行以下几种情况:
1.get方