httpClient4.3使用

1.需要的jar包 httpClient下载

2.使用示例:

	/**
	 * 
	 * 方法说明:使用百度place v2.0 采集位置坐标
	 * @author admin 2013-12-11 上午08:39:45
	 * @param houses : 位置名称
	 * @param city : 城市
	 * @return
	 */
	public PlaceResultData pickup(String houses,String city){
		CloseableHttpClient client = null;
		PlaceResultData data = null;
		try {
			String housesTo = URLEncoder.encode(houses, "UTF-8");
			String regionTo = URLEncoder.encode(city, "UTF-8");
			String url = "http://api.map.baidu.com/place/v2/search?ak="自己的key"&output=json&query=" + housesTo+ "&page_size=1&page_num=0&scope=1&region=" + regionTo;
			client = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//设置请求和传输超时时间
			httpPost.setConfig(requestConfig);
			HttpResponse response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
                String json = EntityUtils.toString(entity, "UTF-8");
                ObjectMapper mapper = new ObjectMapper();
                data =  mapper.readValue(json, PlaceResultData.class);
            }
		} catch (UnsupportedEncodingException e) {
			logger.error(e);
		} catch (ConnectTimeoutException e) {
			System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++");
			System.out.println("连接超时 位置名称:" + houses);
			System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++");
			data = pickup(houses, city);
			logger.error("连接超时 位置:" + houses);
		} catch (SocketTimeoutException e) {
			System.out.println("》》》》》》》》》》》》》》》》》》》》》》》》》》》");
			System.out.println("网络异常 位置名称:" + houses);
			System.out.println("》》》》》》》》》》》》》》》》》》》》》》》》》》》");
			data = pickup(houses, city);
			logger.error("网络异常 位置名称:" + houses);

		}catch (UnrecognizedPropertyException e) {
			System.out.println("-------------------------------------------------");
			System.out.println("转换json数据失败的位置:" + houses);
			System.out.println("-------------------------------------------------");
			logger.error("转换json数据失败的位置:" + houses);
		} catch (EOFException e) {
			System.out.println("**************************************************");
			System.out.println("EOFException异常 位置名称:" + houses);
			System.out.println("**************************************************");
			data = pickup(houses, city);
			logger.error("EOFException异常:" + e);
		} catch (IOException e) {
			System.out.println("《《《《《《《《《《《《《《《《《《《《《《《《《《《");
			System.out.println("IO异常 位置名称:" + houses);
			System.out.println("《《《《《《《《《《《《《《《《《《《《《《《《《《《");
			logger.error("IO异常:" + e);
		} finally{
			try {
				client.close();
			} catch (IOException e) {
				logger.error(e);
			} 
		}
		return data;
	}
注:此示例方法中涉级到的jar包除了httpClient的包,还有 jackson.jar log4j.jar 其中的关联jar包我这里就不列出来了

你可能感兴趣的:(httpclient,http)