五、利用httpclient测试手机号码归属地接口

indexof()用法

package com.netease;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;

public class HttpClientJemter {

    public static CloseableHttpClient httpClient = null;

    @BeforeClass
    public static  void setUp(){
        httpClient = HttpClients.createDefault();
    }
    @Test
    public void phoneTest() throws ClientProtocolException , IOException {
        String phone = "13521275380";
        HttpGet httpGet = new HttpGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel="+phone);
        httpGet.addHeader("EagleEye-TraceId","0b5205fc15872856373491041e0635");
        CloseableHttpResponse res = httpClient.execute(httpGet);
        try{
            int statusCode = res.getStatusLine().getStatusCode();
            System.out.println(statusCode);
            String resBody = EntityUtils.toString(res.getEntity());
            System.out.println(resBody);
            int t1 = resBody.indexOf("province")+9;
            int t2 = resBody.indexOf("\'",t1);
            String city = resBody.substring(t1,t2);  //根据两个双引号截取city的内容
            city = StringEscapeUtils.unescapeJava(city);//将转换成中文,即可获得归属地
            System.out.println(city);

        }finally {
            res.close();
        }
    }
}

 

posted @ 2020-04-19 22:00  李清欣  阅读(257)  评论(0编辑  收藏  举报