HTTP请求代理类,后台post提交数据

星期四, 2008-09-25 | Author: liyz | JAVA-and-J2EE | 11,947 views

经测试,可以完成正常读取和提交,要想读取并解析其中内容还要借助html解析了,感觉像是做内容采集了,代码如下,仅是个代理类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/**
 * Title:         HttpRequestProxy.java
 * Type:        com.liyz.http.HttpRequestProxy
 * Company:
 */
package com.liyz.http;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
 
import org.apache.log4j.Logger;
 
/**
 * HTTP请求代理类
 */
public class HttpRequestProxy
{
    /**
     * 连接超时
     */
    private static int connectTimeOut = 5000;
 
    /**
     * 读取数据超时
     */
    private static int readTimeOut = 10000;
 
    /**
     * 请求编码
     */
    private static String requestEncoding = "utf-8";
 
    private static Logger logger = Logger.getLogger(HttpRequestProxy.class);
 
    /**
     * 发送带参数的GET的HTTP请求
     *
     * @param reqUrl HTTP请求URL
     * @param parameters 参数映射表
     * @return HTTP响应的字符串
     */
    @SuppressWarnings("unchecked")
	public static String doGet(String reqUrl, Map parameters,
            String recvEncoding)
    {
        HttpURLConnection url_con = null;
        String responseContent = null;
        try
        {
            StringBuffer params = new StringBuffer();
            for (Iterator iter = parameters.entrySet().iterator(); iter
                    .hasNext();)
            {
                Entry element = (Entry) iter.next();
                params.append(element.getKey().toString());
                params.append("=");
                params.append(URLEncoder.encode(element.getValue().toString(),
                        HttpRequestProxy.requestEncoding));
                params.append("&");
            }
 
            if (params.length() > 0)
            {
                params = params.deleteCharAt(params.length() - 1);
            }
 
            URL url = new URL(reqUrl);
            url_con = (HttpURLConnection) url.openConnection();
            url_con.setRequestMethod("GET");
            System.setProperty("sun.net.client.defaultConnectTimeout", String
                    .valueOf(HttpRequestProxy.connectTimeOut));// (单位:毫秒)jdk1.4换成这个,连接超时
            System.setProperty("sun.net.client.defaultReadTimeout", String
                    .valueOf(HttpRequestProxy.readTimeOut)); // (单位:毫秒)jdk1.4换成这个,读操作超时
            // url_con.setConnectTimeout(5000);//(单位:毫秒)jdk
            // 1.5换成这个,连接超时
            // url_con.setReadTimeout(5000);//(单位:毫秒)jdk 1.5换成这个,读操作超时
            url_con.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            url_con.getOutputStream().write(b, 0, b.length);
            url_con.getOutputStream().flush();
            url_con.getOutputStream().close();
 
            InputStream in = url_con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                    recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer temp = new StringBuffer();
            String crlf=System.getProperty("line.separator");
            while (tempLine != null)
            {
                temp.append(tempLine);
                temp.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = temp.toString();
            rd.close();
            in.close();
        }
        catch (IOException e)
        {
            logger.error("网络故障", e);
        }
        finally
        {
            if (url_con != null)
            {
                url_con.disconnect();
            }
        }
 
        return responseContent;
    }
 
    /**
     * 发送不带参数的GET的HTTP请求
     *
     * @param reqUrl HTTP请求URL
     * @return HTTP响应的字符串
     */
    public static String doGet(String reqUrl, String recvEncoding)
    {
        HttpURLConnection url_con = null;
        String responseContent = null;
        try
        {
            StringBuffer params = new StringBuffer();
            String queryUrl = reqUrl;
            int paramIndex = reqUrl.indexOf("?");
 
            if (paramIndex > 0)
            {
                queryUrl = reqUrl.substring(0, paramIndex);
                String parameters = reqUrl.substring(paramIndex + 1, reqUrl
                        .length());
                String[] paramArray = parameters.split("&");
                for (int i = 0; i < paramArray.length; i++)
                {
                    String string = paramArray[i];
                    int index = string.indexOf("=");
                    if (index > 0)
                    {
                        String parameter = string.substring(0, index);
                        String value = string.substring(index + 1, string
                                .length());
                        params.append(parameter);
                        params.append("=");
                        params.append(URLEncoder.encode(value,
                                HttpRequestProxy.requestEncoding));
                        params.append("&#038;");
                    }
                }
 
                params = params.deleteCharAt(params.length() - 1);
            }
 
            URL url = new URL(queryUrl);
            url_con = (HttpURLConnection) url.openConnection();
            url_con.setRequestMethod("GET");
            System.setProperty("sun.net.client.defaultConnectTimeout", String
                    .valueOf(HttpRequestProxy.connectTimeOut));// (单位:毫秒)jdk1.4换成这个,连接超时
            System.setProperty("sun.net.client.defaultReadTimeout", String
                    .valueOf(HttpRequestProxy.readTimeOut)); // (单位:毫秒)jdk1.4换成这个,读操作超时
            // url_con.setConnectTimeout(5000);//(单位:毫秒)jdk
            // 1.5换成这个,连接超时
            // url_con.setReadTimeout(5000);//(单位:毫秒)jdk 1.5换成这个,读操作超时
            url_con.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            url_con.getOutputStream().write(b, 0, b.length);
            url_con.getOutputStream().flush();
            url_con.getOutputStream().close();
            InputStream in = url_con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                    recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer temp = new StringBuffer();
            String crlf=System.getProperty("line.separator");
            while (tempLine != null)
            {
                temp.append(tempLine);
                temp.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = temp.toString();
            rd.close();
            in.close();
        }
        catch (IOException e)
        {
            logger.error("网络故障", e);
        }
        finally
        {
            if (url_con != null)
            {
                url_con.disconnect();
            }
        }
 
        return responseContent;
    }
 
    /**
     * 发送带参数的POST的HTTP请求
     *
     * @param reqUrl HTTP请求URL
     * @param parameters 参数映射表
     * @return HTTP响应的字符串
     */
    @SuppressWarnings("unchecked")
	public static String doPost(String reqUrl, Map parameters,
            String recvEncoding)
    {
        HttpURLConnection url_con = null;
        String responseContent = null;
        try
        {
            StringBuffer params = new StringBuffer();
            for (Iterator iter = parameters.entrySet().iterator(); iter
                    .hasNext();)
            {
                Entry element = (Entry) iter.next();
                params.append(element.getKey().toString());
                params.append("=");
                params.append(URLEncoder.encode(element.getValue().toString(),
                        HttpRequestProxy.requestEncoding));
                params.append("&#038;");
            }
 
            if (params.length() > 0)
            {
                params = params.deleteCharAt(params.length() - 1);
            }
 
            URL url = new URL(reqUrl);
            url_con = (HttpURLConnection) url.openConnection();
            url_con.setRequestMethod("POST");
            System.setProperty("sun.net.client.defaultConnectTimeout", String
                    .valueOf(HttpRequestProxy.connectTimeOut));// (单位:毫秒)jdk1.4换成这个,连接超时
            System.setProperty("sun.net.client.defaultReadTimeout", String
                    .valueOf(HttpRequestProxy.readTimeOut)); // (单位:毫秒)jdk1.4换成这个,读操作超时
            // url_con.setConnectTimeout(5000);//(单位:毫秒)jdk
            // 1.5换成这个,连接超时
            // url_con.setReadTimeout(5000);//(单位:毫秒)jdk 1.5换成这个,读操作超时
            url_con.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            url_con.getOutputStream().write(b, 0, b.length);
            url_con.getOutputStream().flush();
            url_con.getOutputStream().close();
 
            InputStream in = url_con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in,
                    recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer tempStr = new StringBuffer();
            String crlf=System.getProperty("line.separator");
            while (tempLine != null)
            {
                tempStr.append(tempLine);
                tempStr.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = tempStr.toString();
            rd.close();
            in.close();
        }
        catch (IOException e)
        {
            logger.error("网络故障", e);
        }
        finally
        {
            if (url_con != null)
            {
                url_con.disconnect();
            }
        }
        return responseContent;
    }
 
    /**
     * @return 连接超时(毫秒)
     * @see com.liyz.http.HttpRequestProxy#connectTimeOut
     */
    public static int getConnectTimeOut()
    {
        return HttpRequestProxy.connectTimeOut;
    }
 
    /**
     * @return 读取数据超时(毫秒)
     * @see com.liyz.http.HttpRequestProxy#readTimeOut
     */
    public static int getReadTimeOut()
    {
        return HttpRequestProxy.readTimeOut;
    }
 
    /**
     * @return 请求编码
     * @see com.liyz.http.HttpRequestProxy#requestEncoding
     */
    public static String getRequestEncoding()
    {
        return requestEncoding;
    }
 
    /**
     * @param connectTimeOut 连接超时(毫秒)
     * @see com.liyz.http.HttpRequestProxy#connectTimeOut
     */
    public static void setConnectTimeOut(int connectTimeOut)
    {
        HttpRequestProxy.connectTimeOut = connectTimeOut;
    }
 
    /**
     * @param readTimeOut 读取数据超时(毫秒)
     * @see com.liyz.http.HttpRequestProxy#readTimeOut
     */
    public static void setReadTimeOut(int readTimeOut)
    {
        HttpRequestProxy.readTimeOut = readTimeOut;
    }
 
    /**
     * @param requestEncoding 请求编码
     * @see com.liyz.http.HttpRequestProxy#requestEncoding
     */
    public static void setRequestEncoding(String requestEncoding)
    {
        HttpRequestProxy.requestEncoding = requestEncoding;
    }
 
    /**
	 * @param args
	 *            http://localhost/bbs/register2.php?username=test002&#038;password=123456
	 *            &#038;[email protected]&#038;locationnew=香港
     * @throws UnsupportedEncodingException
	 * @throws IOException
	 */
    public static void main(String[] args)
    {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", "testing008");
        map.put("password", "123456");
        map.put("email", "[email protected]");
 
        map.put("locationnew", "香港");
 
        String temp = HttpRequestProxy.doPost("http://192.168.101.118/bbs/register2.php", map, "utf-8");
        System.out.println("返回的消息是:"+temp);
 
    }
}

Tags:

文章作者: liyz

本文地址: https://www.pomelolee.com/58.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

No comments yet.

Leave a comment

Search

文章分类

Links

Meta