码迷,mamicode.com
首页 > 其他好文 > 详细

使用特定功能代码

时间:2017-09-26 11:56:11      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:final   rest   builder   auto   src   value   led   util   apach   

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;
    }
}
View Code

  2)关键代码

技术分享
public void autoGetAdCode(String gaodeApi) {
        try {
            String result1 = HttpUtil.get(gaodeApi);
            JSONObject result = JSONObject.parseObject(result1);
            JSONArray provinces =result.getJSONArray("districts").getJSONObject(0).getJSONArray("districts");
            for (Object object : provinces) {//遍历省
                JSONObject province = JSONObject.parseObject(object.toString());
                String name = province.getString("name");
                String level = province.getString("level");
                String adcode = province.getString("adcode");
                String center = province.getString("center");
                regionalStaMapper.insertDivistion(name,level,adcode,center);
                //省信息存入数据库
                for (Object object2 : province.getJSONArray("districts")) {//遍历市
                    JSONObject city = JSONObject.parseObject(object2.toString());
                    //市信息存入数据库
                    name = city.getString("name");
                    level = city.getString("level");
                    adcode = city.getString("adcode");
                    center = city.getString("center");
                    regionalStaMapper.insertDivistion(name,level,adcode,center);
                    if(!level.equals("city")){
                        System.out.println(level);
                        continue;
                    }
                    for (Object object3 : city.getJSONArray("districts")) {//遍历区
                        JSONObject district = JSONObject.parseObject(object3.toString());
                        //区信息存入数据库
                        name = district.getString("name");
                        level = district.getString("level");
                        adcode = district.getString("adcode");
                        center = district.getString("center");
                        regionalStaMapper.insertDivistion(name,level,adcode,center);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.toString());
            throw new RuntimeException();
        }
        
    }
View Code
技术分享
    @Insert("insert into ty_conf_division(adcode,center,level,name) values(#{adcode},#{center},#{level},#{name})")
    Integer insertDivistion(@Param("name")String name, @Param("level")String level, @Param("adcode")String adcode, @Param("center")String center);
View Code

  3)思路

通过高德地图api:http://lbs.amap.com/api/webservice/guide/api/district中的
  http://restapi.amap.com/v3/config/district?key=您的key&keywords=中国&subdistrict=3&extensions=base获得所有数据
注意:可能出现的key需要验证,出错又查看提示的习惯

 

使用特定功能代码

标签:final   rest   builder   auto   src   value   led   util   apach   

原文地址:http://www.cnblogs.com/xiaoping1993/p/7595749.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!