param) {
CloseableHttpResponse response = null;
String resultString = "";
try (
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
) {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
ListparamList = new ArrayList();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), CHARSET);
} catch (Exception e) {
LOGGER.error("", e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
LOGGER.error("", e);
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, JSONObject jsonObject) {
return doPostJson(url, jsonObject.toString());
}
public static String doPostJson(String url, String json) {
CloseableHttpResponse response = null;
String resultString = "";
try (
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
) {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), CHARSET);
} catch (Exception e) {
LOGGER.error("", e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
LOGGER.error("", e);
}
}
return resultString;
}
/**
* 通过http访问获取json数据
*
* @param targetURL
* @return
* @throws IOException
*/
public static String getJsonString(String targetURL) throws IOException {
String res = "";
StringBuilder buffer = new StringBuilder();
URL url = new URL(targetURL);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
if (200 == urlCon.getResponseCode()) {
InputStream is = urlCon.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String str = null;
while ((str = br.readLine()) != null) {
buffer.append(str);
}
br.close();
isr.close();
is.close();
res = buffer.toString();
// res = res.substring(19,res.indexOf(");"));
}
return res;
}
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", 1000012342378L);
JSONObject data = new JSONObject();
data.put("mode", "sync");
data.put("terminals", 333);
JSONObject content = new JSONObject();
content.put("id", "1");
content.put("l1", "333");
content.put("l2", "333");
content.put("l3", "333");
data.put("content", content);
jsonObject.put("data", data);
System.out.println(jsonObject);
String s = HttpClientUtil.doPostJson("http://192.168.13.123:9530/uploadById.do", jsonObject);
System.out.println(s);
}
}