1.通过高德api将我国省市区存入数据库
1)用到的工具类
package com.ty.tyzxtj.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; /** * http工具类 * @author wangjiping * */ public class HttpUtil { // 超时时间 public static final int TIME_OUT = 50000; public static String post(String postUrl){ String response = ""; PostMethod postMethod = new PostMethod(postUrl); try { HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams() .setConnectionTimeout(50000);// 设置连接时间 int status = client.executeMethod(postMethod); if (status == HttpStatus.SC_OK) { InputStream inputStream = postMethod.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader( inputStream)); StringBuffer stringBuffer = new StringBuffer(); String str = ""; while ((str = br.readLine()) != null) { stringBuffer.append(str); } response = stringBuffer.toString(); } else { response = "fail"; } } catch (Exception e) { e.printStackTrace(); } finally { // 释放连接 postMethod.releaseConnection(); } return response; } public static String loadJson (String url) { StringBuilder json = new StringBuilder(); try { URL urlObject = new URL(url); URLConnection uc = urlObject.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String inputLine = null; while ( (inputLine = in.readLine()) != null) { json.append(inputLine); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return json.toString(); } public static String get(String url){ String html = ""; // 构造HttpClient的实例 HttpClient httpClient = new HttpClient(); // 创建GET方法的实例 GetMethod getMethod = new GetMethod(url); // 使用系统提供的默认的恢复策略 不重试 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); getMethod.setRequestHeader("Connection" , "Keep-Alive"); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIME_OUT); httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIME_OUT); try { // 执行getMethod int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + getMethod.getStatusLine()); } // 处理内容 html = getMethod.getResponseBodyAsString(); } catch (Exception e) { } finally { // 释放连接 getMethod.releaseConnection(); } return html; } }