用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();
        }

	}
}

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用HttpClient调用天气预报接口的Spring Boot示例: 1. 添加HttpClientJackson依赖 ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> ``` 2. 创建HttpClient实例 ```java @Configuration public class HttpClientConfig { @Bean public CloseableHttpClient httpClient() { return HttpClients.createDefault(); } @Bean public HttpClientService httpClientService(CloseableHttpClient httpClient) { return new HttpClientService(httpClient); } } ``` 3. 创建HttpClientService类 ```java public class HttpClientService { private final CloseableHttpClient httpClient; public HttpClientService(CloseableHttpClient httpClient) { this.httpClient = httpClient; } public String get(String url) throws IOException { HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = httpClient.execute(httpGet); try { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } } finally { response.close(); } return null; } } ``` 4. 创建Weather类 ```java public class Weather { private String date; private String week; private String weather; private String temp; private String humidity; private String wind; // getter and setter } ``` 5. 创建WeatherService类 ```java @Service public class WeatherService { private final HttpClientService httpClientService; public WeatherService(HttpClientService httpClientService) { this.httpClientService = httpClientService; } public List<Weather> getWeather(String city) throws IOException { String url = "http://wthrcdn.etouch.cn/weather_mini?city=" + city; String json = httpClientService.get(url); ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(json); JsonNode dataNode = rootNode.path("data"); List<Weather> weatherList = new ArrayList<>(); for (JsonNode node : dataNode.path("forecast")) { Weather weather = mapper.treeToValue(node, Weather.class); weatherList.add(weather); } return weatherList; } } ``` 6. 测试WeatherService ```java @RestController public class WeatherController { private final WeatherService weatherService; public WeatherController(WeatherService weatherService) { this.weatherService = weatherService; } @GetMapping("/weather") public List<Weather> getWeather(@RequestParam String city) throws IOException { return weatherService.getWeather(city); } } ``` 现在,你可以通过访问http://localhost:8080/weather?city=北京来获取北京的天气预报信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值