Java 通过HttpClient Post方式提交json请求

package com.sinosoft.ap.harmfullibrary.util;

/**
* 发送post请求
*/
import net.sf.json.JSONObject;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
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.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {


public static void post(JSONObject json, String url) {
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
System.out.println(json.toString());

HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");

// 解决中文乱码问题
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");

httpPost.setEntity(stringEntity);

System.out.println("Executing request " + httpPost.getRequestLine());

ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(final HttpResponse response)
throws ClientProtocolException, IOException {//
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {

HttpEntity entity = response.getEntity();

return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException(
"Unexpected response status: " + status);
}
}
};
String responseBody = httpclient.execute(httpPost, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);

} catch (Exception e) {
System.out.println(e);
}


}

public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("UpdateCode", "update");
obj.put("harmful_info_id", "014e79cb198579840a504c89cb17c10f");
obj.put("harmful_info_desc", "新疆&暴");
post(obj, "http://10.10.40.3:5002/updateKeywordRules");
}
}

posted @ 2017-08-22 17:58  超凡2012  阅读(4982)  评论(0编辑  收藏  举报