kongzy
2023-11-28 59d9ea33f503e363f2e2941c7c00cc9dd9d9d1c7
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
package com.nanometer.smartlab.service;
 
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
 
/**
 * Created by johnny on 15/11/18.
 */
@Service
public class HttpClientService {
    private final static String ENCODING = "UTF-8";
 
    @Resource
    private HttpClient httpClient;
 
    public String httpGet(String url) throws IOException {
        HttpGet get = new HttpGet(url);
        try {
            HttpResponse response = this.httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            if (is == null) {
                return null;
            }
            return IOUtils.toString(is, ENCODING);
        } finally {
            get.releaseConnection();
        }
    }
 
    public String httpPost(String url, List<NameValuePair> formParams) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
            HttpResponse response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity());
        } finally {
            httpPost.releaseConnection();
        }
    }
}