httpclient访问接口

/**
* @author Administrator 
* @date 2015年12月9日 上午10:56:38
* @description 根据url获取json数据
* @parameter  
* @return JsonObject数据
* @throws IOException 
* @throws HttpException 
*/
public void getDataByUrl(String url) throws HttpException, IOException {

   //创建httpClient对象   
        HttpClient client = new HttpClient(); 
  
        //创建post请求方法   
        PostMethod post = new PostMethod(url);
        
        //设置请求超时时间   
        client.getHttpConnectionManager().getParams().setConnectionTimeout(30 * 1000);   
        
        //设置代理服务器的ip地址和端口
        client.getHostConfiguration().setProxy("XXX.XX.XX.XXX", 8080);
        
        //使用抢先认证
        client.getParams().setAuthenticationPreemptive(true);  
              
        String responseString = null;    
         
        //设置请求头部类型   
        post.setRequestHeader("Content-Type","text/xml");  
        post.setRequestHeader(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");  
                               
        //获取状态码
        int statusCode = client.executeMethod(post);
        
        //如果访问成功 statusCode == 200
        if(statusCode == HttpStatus.SC_OK){    
            BufferedInputStream bis = new BufferedInputStream(post.getResponseBodyAsStream()); 
            
            byte[] bytes = new byte[1024];    
            ByteArrayOutputStream bos = new ByteArrayOutputStream();    
            
            int count = 0;    
            
            while((count = bis.read(bytes))!= -1){    
                bos.write(bytes, 0, count);    
            }    
            
            byte[] strByte = bos.toByteArray();    
            responseString = new String(strByte,0,strByte.length,"utf-8");  
            
            bos.close();    
            bis.close();    
        }    


        //释放链接
        post.releaseConnection();   
              
        JSONObject json = JSONObject.parseObject(responseString);

//...........................
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用HttpClient调用天气预报接口的Spring Boot示例: 1. 添加HttpClient和Jackson依赖 ```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、付费专栏及课程。

余额充值