post、raw、json调用第三方接口

发布时间 2023-06-13 18:25:29作者: leocat

1、调用第三方接口,对方接口文档写到”请求方式 post json格式、请求参数 json格式“,看不懂,就用postMan试试看。发现只有一种方式能调用通,

 

2、

 

3、Content-Type:application/json

 

 

4、根据上面的方式,所有写了下面的方法:

/**
*
* @param url 接口地址
* @param putData JSONString,不是单纯的字符串
* @param encoding 一般就传“UTF-8”即可
* @return
*/
public static String doPostJson(String url, String putData, String encoding) {
String body = "";
CloseableHttpResponse response = null;
CloseableHttpClient client = HttpClients.createDefault();
// 向指定资源位置上传内容
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8");
httpPost.setHeader( HttpHeaders.ACCEPT,"application/json");
httpPost.setEntity(new StringEntity(putData, Charset.forName("UTF-8")));
try {
response = client.execute(httpPost);
// 通过response中的getEntity()方法获取返回值
HttpEntity entity = response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, encoding);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpPost.abort();
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
}
return body;
}

5、需要的包
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
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;
import java.nio.charset.Charset;
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.14</version>
</dependency>