工作中经常遇到需要调用外部接口的场景 每次都需要百度 故在次记录一下留作备用 代码可复用
依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
代码
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class A {
public static void main(String[] args) {
//String s = A.callOtherInterface();
}
//场景下url固定 所以只传一个JSON字符串
public static String callOtherInterface(String JSONString) {
HttpClient client = HttpClients.createDefault();
// 要调用的接口方法
String url = "%此处填写url";
HttpPost post = new HttpPost(url);
JSONObject jsonObject = null;
try {
StringEntity s = new StringEntity("%此处填写JSON字符串", "UTF-8");
//s.setContentEncoding("UTF-8");//此处测试发现不能单独设置字符串实体的编码,否则出错!应该在创建对象时创建
s.setContentType("application/json");
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.setConnectionRequestTimeout(CONNECT_TIMEOUT)
.build();
httpPost.setConfig(requestConfig);
post.setEntity(s);
post.addHeader("content-type", "application/json;charset=UTF-8");
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回json格式:
jsonObject = JSONObject.parseObject(EntityUtils.toString(res.getEntity()));
}
} catch (Exception e) {
System.out.println("服务间接口调用出错!");
e.printStackTrace();
//throw new RuntimeException(e);
}
return jsonObject.toString();
}
}