hefeixia
2021-02-18 5b8c95c760840f09910730943b21391e47187315
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
package chat.medeasy;
 
import java.io.Closeable;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import org.apache.http.HttpEntity;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
 
public class HttpClientUtil {
 
    public static String execHttpClient(String jsonStr, String serverURL, Map<String, String> heads) {
        boolean result = false;
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        String responseContent = "";
        
        try {
             httpClient = HttpClientBuilder.create().build();
             httpPost = new HttpPost(serverURL);
             if (heads != null) {
                 for (String head : heads.keySet()) {
                      httpPost.addHeader(head, heads.get(head));
                 }
             }
             httpPost.setEntity(new StringEntity(jsonStr, "UTF-8"));
             response = httpClient.execute(httpPost);
             HttpEntity entity = response.getEntity();
             responseContent = EntityUtils.toString(entity);
             response.close();
             httpClient.close();
        } catch(Exception e) {
             e.printStackTrace();
        } finally {
            close(response, httpClient);
        }
        
        return responseContent;
    }
    
    private static void close(Closeable... closeables) {
        if (closeables != null && closeables.length > 0) {
            try {
                for (Closeable closeable : closeables) {
                    if (closeable != null) {
                        closeable.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }        
    }
}