如何将json数据按顺序发送接口
1、本文记录的内容如下:
1.使用HttpClient相关类,包括PostMethod,RequestEntity,StringRequestEntity等
2.实现用post请求方式发送json数据
2、将第三方提供的接口文档字段构建成model。
public class A{
private String sn;
private String host;
private String port;
3、 ......
public String getHost() {return host;}
public void setHost(String host) {this.host = host;}
...... }
4、Java对象
public class B{
private String id;
private String ip;
private String port;
......
...... }
5、发送请求
public class APITest {
//这里是日志
private static ....
/** * api_url 请求路径 ,换成自己的路径
*/ private String apiUrl = MapCache.getConfigVal("api_url");
/** * http客户端
*/ private HttpClient client = new HttpClient();
/** * 将告警信息发送到百信API * * @param notice
*/ public void sendNotice(B b) {
6、//java对象封装成第三方类
if (b != null) {
A a = new A();
a.setHost(b.getIp); ... send(a); } }
/** * post请求发送json格式的数据至API * * @param A
*/ public void send(A a) {
if (this.apiUrl == null) {
this.apiUrl = "http://xxx..."; }
7、if (this.apiUrl != null) {
PostMethod postMethod = new PostMethod(this.apiUrl);
Gson gson = new Gson();
String data = gson.toJson(a);
try {
8、RequestEntity requestEntity = new StringRequestEntity(data.toString(), "application/json", "utf-8");
postMethod.setRequestEntity(requestEntity);
} catch (UnsupportedEncodingException e) {
log.error("Java Object To JSON Error: ", e);
}
9、try {
int httpCode = client.executeMethod(postMethod);
if (httpCode == 200) {
sendInfoLog.info("发送到api成功:" + data.toString());
} else {
sendInfoLog.info("发送到api失败:" + data.toString());
} } catch (IOException e) {
this.log.error("发送api post请求失败:", e);
} finally {
postMethod.releaseConnection();
}
}
} }