java 타오바오 API로 json 읽기 및 쓰기 핸드폰 귀속지 조회 기능 코드 구현

일반적으로 핸드폰 귀속지 내용을 조회하면 json 형식으로 저장하기 쉬울 것이다. 인터넷에서 타오바오의 귀속지 API를 찾았고 json과 관련된jar백을 처리하여 이 핸드폰 귀속지 조회 기능을 했다

package com.think.java;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class TestMobileCity {   

    /**
     * , API
     * @param mobileNumber
     * @return
     * @throws MalformedURLException
     */
    public static String calcMobileCity(String mobileNumber) throws MalformedURLException{
        String jsonString = null;
        JSONArray array = null;
        JSONObject jsonObject = null;
        String urlString = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=" + mobileNumber;
        StringBuffer sb = new StringBuffer();
        BufferedReader buffer;
        URL url = new URL(urlString);
        try{
            InputStream in = url.openStream();

            //
            buffer = new BufferedReader(new InputStreamReader(in,"gb2312"));
            String line = null;
            while((line = buffer.readLine()) != null){
                sb.append(line);
            }
            in.close();
            buffer.close();
            // System.out.println(sb.toString());
            jsonString = sb.toString();
            // “__GetZoneResult_ = ”, JSONArray
            jsonString = jsonString.replaceAll("^[__]\\w{14}+[_ = ]+", "[");
            // System.out.println(jsonString+"]");
            String jsonString2 = jsonString + "]";
            // STRING json
            array = JSONArray.fromObject(jsonString2);

            // JSONArray JSONObject , array
            jsonObject = array.getJSONObject(0);       

        }catch(Exception e){
            e.printStackTrace();
        }
        return jsonObject.getString("province");
    }

    /**
     *
     * @param mobileNumbers
     * @return
     * @throws MalformedURLException
     */
    public static JSONObject calcMobilesCities(List<String> mobileNumbers) throws MalformedURLException{
        JSONObject jsonNumberCity = new JSONObject();
        for(String mobileNumber : mobileNumbers){
            jsonNumberCity.put(mobileNumber, calcMobileCity(mobileNumber));            ;
        }       
        return jsonNumberCity;
    }

    public static void main(String[] args) throws Exception{
        String testMobileNumber = "1881758452";
        System.out.println(calcMobileCity(testMobileNumber));
        List<String> mobileList = new ArrayList<String>();
        for(int i = 1350345; i < 1350388; i++){
            mobileList.add(String.valueOf(i));
        }
        System.out.println(calcMobilesCities(mobileList).toString());
    }
}

좋은 웹페이지 즐겨찾기