利用百度API簡單實現IP地位

package GeographicalLocation;

import java.util.ArrayList;

import net.sf.json.JSONObject;
import MyHttpClient.MyHttpClient;

public class GeoLocation {

	private String url = "    //ak是百度提供的爲調用使用的,具體介紹可看百度開發者社區 
	private String jsonStr;
	private String city;
	private String district;
	private String province;
	
	public GeoLocation(){
		
		MyHttpClient httpClient_location = new MyHttpClient();
		jsonStr = httpClient_location.getContentByURL(url);
		//System.out.println(jsonStr);
		this.parseJSONData();
	}
	
	private void parseJSONData(){
		
		try {
			
			JSONObject obj = JSONObject.fromObject(jsonStr);//此處可簡化
			String content = obj.getString("content");
			//System.out.println(content);
			
			JSONObject obj2 = JSONObject.fromObject(content);
			//System.out.println(obj2.toString());
			String address_detail = obj2.getString("address_detail");
			
			JSONObject obj3 = JSONObject.fromObject(address_detail);
			city = obj3.getString("city");
			//System.out.println("城市: "+city);
			
			district = obj3.getString("district");
			if(district.equals("")){              //由於提供的信息中district有的地方爲                                                               //空,因此爲空時與city相同
				
				district = city;
			}
			//System.out.println("區縣: "+district);
			
			province = obj3.getString("province");
			//System.out.println("省份: "+province);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public ArrayList<String> getGeoLocation(){
		
		ArrayList<String> location = new ArrayList<String>();
		location.add(province);
		location.add(district);
		location.add(city);
		
		return location;
	}
	
	public static void main(String[] args){
		
		GeoLocation geoLocation = new GeoLocation();
		//System.out.println(geoLocation.getProvince());
		//System.out.println(geoLocation.getDistrict());
		//System.out.println(geoLocation.getCity());
	}
}

package MyHttpClient;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class MyHttpClient {

	public String getContentByURL(String url){
		
		String str = null;
		try{
			CloseableHttpClient httpclient = HttpClients.createDefault();
			HttpGet httpget = new HttpGet(url);
			CloseableHttpResponse response = httpclient.execute(httpget);
			try{
				HttpEntity entity = response.getEntity();
				if(entity != null){
						str = EntityUtils.toString(entity);
						//System.out.println(str);
				}
			}finally{
					response.close();
				}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return str;
	}
	public static void main(String[] args){
		
		String url = "http://m.weather.com.cn/data5/city.xml";
		MyHttpClient myHttpClient = new MyHttpClient();
		myHttpClient.getContentByURL(url);
	}
	
}
相關文章
相關標籤/搜索