控制层,将要推送的json数据进行封装
public void Pushdata() {
JSONObject json = new JSONObject();
//此处封装json数据
//调用工具类中的方法,传入url以及json数据进行推送
try {
String bd = CommonUtil.sendPut("url", json, "UTF-8");
JSONObject object = JSON.parseObject(bd); //获取对方返回的数据
//String ss = object .getString("data");
} catch (ParseException | IOException e) {
e.printStackTrace();
}
}
在pom.xml中加入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.7</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client</artifactId>
<version>1.22.0</version>
</dependency>
工具类中的数据推送方法
/**
* HttpClient 推送数据
*
* @param url 接口地址
* @param json 传入的参数
* @return String
*/
public static String sendPut(String url, JSONObject putData, String encoding) throws ParseException, IOException {
String body = "";
System.err.println(putData.toJSONString());//打印了一下我推送的json数据
CloseableHttpResponse response = null;
CloseableHttpClient client = HttpClients.createDefault();
//向指定资源位置上传内容
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setEntity(new StringEntity(JSONObject.toJSONString(putData)));
try {
response = client.execute(httpPost);
System.err.println("status" + response.getStatusLine().getStatusCode());
//通过response中的getEntity()方法获取返回值
HttpEntity entity = response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, encoding);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
httpPost.abort();
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
}
System.err.println("body:" + body);
return body;
}