HttpClient请求及下载文件

添加maven依赖

1
2
3
4
5
6
7
8
9
10
<dependency>
<artifactId>httpclient</artifactId>
<groupId>org.apache.httpcomponents</groupId>
<version>4.4.1</version>
</dependency>
<dependency>
<artifactId>httpcore</artifactId>
<groupId>org.apache.httpcomponents</groupId>
<version>4.4.1</version>
</dependency>

HttpClient发送Get请求

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
import java.io.IOException;
import java.net.HttpURLConnection;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
* @author lm
*
*/
public class SimpleHttpGeter {

public String doGet(String url) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
if (response != null && response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
return EntityUtils.toString(response.getEntity());
}
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
response.close();
httpclient.close();
}
return null;
}

public String doGet(String url, String[] paramNames, String[] paramValues) throws IOException {
StringBuilder sb = new StringBuilder(url);
sb.append("?");
for (int i = 0; i < paramNames.length; i++) {
sb.append(paramNames[i] + "=" + paramValues[i] + "&");
}
sb.deleteCharAt(sb.length() - 1);
return doGet(sb.toString());
}

}

HttpClient发送Post请求

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
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
* @author lm
*
*/
public class SimpleHttpPoster {

public String doPost(String url) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
if (response != null && response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
return EntityUtils.toString(response.getEntity());
}
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
response.close();
httpclient.close();
}
return null;
}

public String doPost(String url, String[] paramNames, String[] paramValues) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
// 迭代参数
for (int i = 0; i < paramNames.length; i++) {
nvps.add(new BasicNameValuePair(paramNames[i], paramValues[i]));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
if (response != null && response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
return EntityUtils.toString(response.getEntity());
}
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
response.close();
httpclient.close();
}
return null;
}

public String doBody(String url, String parmas) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.addHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Accept", "application/json");
post.setEntity(new StringEntity(parmas, Charset.forName("utf-8")));
CloseableHttpResponse response = httpclient.execute(post);
try {
if (response != null && response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
return EntityUtils.toString(response.getEntity());
}
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
response.close();
httpclient.close();
}
return null;
}

}

HttpClient下载文件

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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/**
* @author lm
*
*/
public class HttpDownload {
private static final int WRITE_SIZE = 4096;

public boolean download(String url, String filePath) throws IOException {
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
FileOutputStream outputStream = null;
try {
httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == 200) {
File file = new File(filePath);
outputStream = new FileOutputStream(file);
InputStream inputStream = httpResponse.getEntity().getContent();
byte buff[] = new byte[WRITE_SIZE];
int counts = 0;
while ((counts = inputStream.read(buff)) != -1) {
outputStream.write(buff, 0, counts);
}
outputStream.flush();
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
if (outputStream != null) {
outputStream.close();
}
if (httpClient != null) {
httpClient.close();
}
if (httpResponse != null) {
httpResponse.close();
}
}
return true;
}

}

不使用HttpClient下载文件

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

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpDownload {

public static void downloadFile(String url, String filePath, String method) throws Exception {
FileOutputStream fileOut = null;
HttpURLConnection conn = null;
InputStream inputStream = null;
try {
// 建立链接
URL httpUrl = new URL(url);
conn = (HttpURLConnection) httpUrl.openConnection();
// 以Post方式提交表单,默认get方式
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
// post方式不能使用缓存
conn.setUseCaches(false);
// 连接指定的资源
conn.connect();
// 获取网络输入流
inputStream = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
// 写入到文件(注意文件保存路径的后面一定要加上文件的名称)
fileOut = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOut);
byte[] buf = new byte[4096];
int length = bis.read(buf);
// 保存文件
while (length != -1) {
bos.write(buf, 0, length);
length = bis.read(buf);
}
bos.close();
bis.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}

}