httpClient如何调用第三方接口

最近因工作需要调用第三方接口,所以用到了httpClient,多年不用,手生了很多,于是再次记录下此次开发过程.

方法如下:先导入依赖

		
			org.apache.httpcomponents 
			httpclient
			4.5.5 
		
	@SuppressWarnings("unused")
	@Override
	public String getCar300Price(String modelId, String zone) {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		try {
			StringBuffer params = new StringBuffer();
			JSONObject param = new JSONObject();
			param.put("modelId", modelId);
			param.put("zone", zone);
			// 创建Post请求
			HttpPost httpPost = new HttpPost(url);
			StringEntity entity = null;
			entity = new StringEntity(param.toString(),"UTF-8");
			httpPost.setEntity(entity);
			httpPost.setHeader("Content-Type", "application/json");
			CloseableHttpResponse response = httpClient.execute(httpPost);
			HttpEntity responseEntity = response.getEntity();
			String s = EntityUtils.toString(responseEntity, "UTF-8");
			JSONObject jsonObject = JSONObject.parseObject(s);
			String code = jsonObject.getString("code");
			String data = jsonObject.getString("data");
			if("OK".equals(code)){
				return data;
			}else {
				return null;
			}

		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally {
			HttpClientUtils.closeQuietly(httpClient);
		}

		return null;
	}

 在类中,我们用这个来读取.properties文件

    @Value("${getPath.url}")
    private String url;

 

 这是我名为application-develop的.properties文件

getPath.url=http://**.**.***.107:5088/vehicleModelLibrary/getNewPrice

以上就是所有内容,欢迎大家参考,如有问题,希望诸位可以指出,笔者感激不尽

 

 

你可能感兴趣的:(httpClient)