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包我這裏就不列出來了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章