工具类:httpurlconnection模板

源码:

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
package com.cnbool.util;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


*
* @version 1.0
*
*/

public class {
public static final String GET = "GET";
public static final String POST = "POST";
private String mothod = GET;
private InputStream in = null;
private HttpURLConnection httpConn = null;

public interface DownloadHander {
public void handle(InputStream in);
public void handleErr(InputStream in, int respCode);
}

public void download(URL url, DownloadHander downloadHander) throws Exception {
try {
httpConn = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(true);
httpConn.setRequestMethod(mothod);

if (httpConn.getResponseCode() == 200) {
in = httpConn.getInputStream();
if (downloadHander != null) {
downloadHander.handle(in);
}
} else {
in = httpConn.getErrorStream();
if (downloadHander != null) {
downloadHander.handleErr(in, httpConn.getResponseCode());
}
}
} catch (Exception e) {
throw e;
} finally {
if (in != null) {
in.close();
}
if (httpConn != null) {
httpConn.disconnect();
}
}
}

public void setRequestMethod(String method) {
this.mothod = method;
}
}