用HTTPclient和Jackson向接口发送json数据

公司有个业务要向实时数据平台调用接口以获得实时数据。
接口文档如下
在这里插入图片描述
请求数据种的loginId,tonce,ciphertext可以为空。

所用到的第三方jar包有:

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
</dependency>
<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
</dependency>

思路:
1.创建发送请求json的解析类

@Data
public class SendWsdData {

    private Integer loginId;

    private String tonce;

    private String ciphertext;

    private String channelIds;

}

2.创建一个将实体类对象解析为json的工具类

/**
* 本次业务所用到的是第二个方法
*/
public class JsonUtil {
	
	//将json反序列化为对象数据
    public static Object jsonToObj(String data, Class cls) throws IOException {
        return new ObjectMapper().readValue(data, cls);
    }
    
	//将对象序列化为json数据
    public static String objTojson(Object obj) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException{
                gen.writeString("");
            }
        });
        return objectMapper.writeValueAsString(obj);
    }

	//将json序列化为数组
    public static JsonNode jsonToArray(String data) throws IOException {
        return new ObjectMapper().readTree(data);
    }
}

3.做一个发送post请求的工具类

public final class HttpUtil {

	public static String postJson(String url, String json) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        //设置请求超时时间和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
        post.setConfig(requestConfig);
        
        post.addHeader("Content-Type", "application/json");

        StringEntity se = new StringEntity(json);
        post.setEntity(se);

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(post);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (httpResponse != null && statusCode == HttpStatus.SC_OK){
                HttpEntity entity = httpResponse.getEntity();

                if (entity != null) {
                    return EntityUtils.toString(entity, "utf-8");
                }
            }

//            System.out.println(statusCode);
        } finally {
            closeHttpClient(httpClient);
        }

        return null;
    }

	private static void closeHttpClient(CloseableHttpClient client) throws IOException {
        if (client != null) {
            client.close();
        }
    }
    
}

4.开始写业务

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestSendWsd {

	@Test
	public void testSendJson(){
		SendWsdData wsdData = new SendWsdData();
        wsdData.setTonce("");
        wsdData.setLoginId(1);
        wsdData.setCiphertext("");
        wsdData.setChannelIds("1000451095,1000451096");
        
		String json = null;
        try {
            json = JsonUtil.objTojson(wsdData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

		String url = "http://xxxx.com:6512/DynEnvService/GetChannelDatasByChannelIDs";
		try {
            String result = HttpUtil.postJson(url, json);
            System.out.println(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

	}
}

最后控制台打印出的结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/czx2018/article/details/83213419
今日推荐