接口调用

httpclient-4.3.1.jar
httpcore-4.3.jar

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
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 static String postRequst(String url, String jsonStr) {
	CloseableHttpClient httpClient = HttpClientBuilder.create().build();

	HttpPost httpPost = new HttpPost(url);
	httpPost.addHeader("content-type", "application/json");
	httpPost.addHeader("Accept", "application/json");
	RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(100000).build();
	httpPost.setConfig(requestConfig);

	StringEntity entity = new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
	httpPost.setEntity(entity);

	CloseableHttpResponse response = null;

	try {
		response = httpClient.execute(httpPost);
		String statusCode = response.getStatusLine().getStatusCode() + "";
		String content = EntityUtils.toString(response.getEntity(), "utf-8");

		System.out.println("code[" + statusCode + "]:" + content);

		return content;
	} catch (ClientProtocolException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}	
fastjson-1.2.29.jar

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

JSONObject jsonObj = new JSONObject();
jsonObj.put("userId", "ssh");
jsonObj.put("userName", "mobai");
String jsonStr = jsonObj.toJSONString();

String record = postRequst("http://127.0.0.1:8080/test/test.do",jsonStr);

猜你喜欢

转载自blog.csdn.net/m0_38084243/article/details/83544113