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();
|
}
|
}
|
}
|
}
|