一、适用场景
当我们向第三方系统提交数据的时候,需要调用第三方系统提供的接口。不同的系统提供的接口也不一样,有的是SOAP Webservice、RESTful Webservice 或其他的。当使用的是RESTful webservice的时候,就可以使用httpcomponents组件来完成调用。
如我们需要发起post请求,并将数据转成json格式,设置到post请求中并提交。
url:"http://www.xxxxx.com/message"
json数据格式 {"name":"zhangsan", "age":20, "gender": "mail"} // 一个用户的基本信息
二、实例代码
package com.demo.test; import java.io.IOException; import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
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.HttpClients;
import org.apache.http.util.EntityUtils; public class Test { public static String sendInfo(String sendurl, String data) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(sendurl);
StringEntity myEntity = new StringEntity(data,
ContentType.APPLICATION_JSON);// 构造请求数据
post.setEntity(myEntity);// 设置请求体
String responseContent = null; // 响应内容
CloseableHttpResponse response = null;
try {
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
responseContent = EntityUtils.toString(entity, "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (response != null)
response.close(); } catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (client != null)
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return responseContent;
} public static void main(String[] args) {
String json = "{\"name\":\"zhangsan\", \"age\":20, \"gender\": \"mail\"} ";
String result = sendInfo("http://www.xxxxx.com/message", json);
System.out.println(result);
}
}
发送请求之后,后台会打印返回的信息。