使用mob提供的接口 查询IP对应的省市区信息(json对象转java对象)

摘要:
登录地址:http://api.mob.com1。编写一个发送请求的工具类。2.定义一个接受返回值的类。3.发送请求。这里是发送请求的工具类;importcom.sun.org.apache.xml.internal.utils。URI;importorg.apache.http.HttpEntity;

登录地址:http://api.mob.com

1、写一个发送请求的工具类

2、定义一个接受返回值的类

3、发送请求

---------这里是发送请求的工具类------------------

package com.haochedai.util;

import com.sun.org.apache.xml.internal.utils.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.jboss.netty.handler.codec.http.HttpHeaders.Values.CHARSET;

/**
* Author:wwei
* DESC:HttpClient工具类
*/
public class HttpClientUtil {


private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

public static String doGet(String url) {
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
String tempTitle = null;
try {
HttpGet httpGet = new HttpGet(url);
// 执行get请求
HttpResponse httpResponse;
httpResponse = closeableHttpClient.execute(httpGet);
// 获取响应消息实体
HttpEntity entity = httpResponse.getEntity();
// 判断响应实体是否为空
if (entity != null) {
return EntityUtils.toString(entity, "UTF-8");
} else {
return null;
}
} catch (Exception e) {
logger.error(tempTitle);
logger.error(e.toString());
} finally {
try {
// 关闭流并释放资源
closeableHttpClient.close();
} catch (IOException e) {
logger.error(e.toString());
}
}
return null;
}


public static String doGet(String url, Map<String, Object> params) {
if(!StringUtils.hasText(url)){
return "";
}
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for (String key : params.keySet()) {
pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, "UTF-8"));
}
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = closeableHttpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
// 判断响应实体是否为空
if (entity != null) {
return EntityUtils.toString(entity, "UTF-8");
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭流并释放资源
closeableHttpClient.close();
} catch (IOException e) {
logger.error(e.toString());
}
}
return null;
}


public static String doPost(RequestObject object) {
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
String tempTitle = null;
try {
HttpPost httpPost = new HttpPost(object.toUrl());
// 执行get请求
HttpResponse httpResponse;
httpResponse = closeableHttpClient.execute(httpPost);
// 获取响应消息实体
HttpEntity entity = httpResponse.getEntity();
// 判断响应实体是否为空
if (entity != null) {
return EntityUtils.toString(entity, "UTF-8");
} else {
return null;
}
} catch (Exception e) {
logger.error(tempTitle);
logger.error(e.toString());
} finally {
try {
// 关闭流并释放资源
closeableHttpClient.close();
} catch (IOException e) {
logger.error(e.toString());
}
}
return null;
}


}

---------------------------------------

----------这里定义一个对象,接收返回值----------

package com.haochedai.bean;

/**
* Created by Administrator on 2017/5/26 0026.
*/
public class AreaBean {
private String city;
private String province;

public AreaBean() {
}

public AreaBean(String city, String province) {
this.city = city;
this.province = province;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getProvince() {
return province;
}

public void setProvince(String province) {
this.province = province;
}

}
-------------------------------
--------这里开始使用-----------

package com.haochedai.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.haochedai.bean.AreaBean;
import com.haochedai.exception.PcsRunTimeException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.http.client.HttpClient;
import org.slf4j.LoggerFactory;

/**
* Created by Administrator on 2017/5/26 0026.
* see: http://api.mob.com
*/
public class IpUtil {
static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(IpUtil.class);

private static final String URL = "http://apicloud.mob.com/ip/query?key=这里需要一个key值,需要自己去注册";


public static AreaBean getArea(String ip) {
if (StringUtils.isBlank(ip)) {
return new AreaBean();
}
JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doGet(URL+"&ip="+ip));
String code = jsonObject.getString("retCode");
if (code.equals("200")) {
return jsonObject.getObject("result", AreaBean.class);
} else {
String msg = jsonObject.getString("msg");
LOGGER.error("IP地址解析异常: errorCode={}, msg={}", code, msg);
throw new PcsRunTimeException(msg);
}
}
//    public static void main(String[] args) {
// System.out.println(IpUtil.getArea("112.27.205.106").getCity()+","+IpUtil.getArea("112.27.205.106").getProvince());
// }

}

免责声明:文章转载自《使用mob提供的接口 查询IP对应的省市区信息(json对象转java对象)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇python模块--os模块soapUI学习笔记--用例字段参数化下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

上手七牛云存储

早就听说过七牛云存储,终于有时间上手实践。 1、第一步,注册七牛账号,由于是测试,首先申请的是个人账号 2、注册成功之后,默认是体验账号,每月只有1G的空间容量及1G的下载流量       3、账号认证,认证成功之后将升级为标准账号,每月有10G的空间容量及20G的下载流量       虽然认证麻烦了些,但看得出来,七牛还是很良心的,这种免费套餐对于一...

黄聪:PHP字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、切割成数组等)

一、字符串替换 str_replace("iwind", "kiki", "i love iwind, iwind said"); 将输出 "i love kiki, kiki said" str_replace(find,replace,string,count)参数 描述  find 必需。规定要查找的值。 replace 必需。规定替换 find...

2021团体程序设计天梯赛 L1-6 吉老师的回归

思路: 字符串处理 Tip: getline和find的应用 #include <bits/stdc++.h> using namespace std; int main() { int n, t, num = 0; string now; cin >> n >> t; getcha...

SALT+HASH撒盐加密

#region 撒盐加密 string salt = Guid.NewGuid().ToString(); byte[] passwordAndSaltBytes = System.Text.Encoding.UTF8.GetBytes(model.Password + salt);...

Android中关于日期时间与时区的使用总结

原文引自:http://www.2cto.com/kf/201312/266908.html 在开发Android的过程中,出现过几次由于日期时间导致的问题,而且主要是由于时区的原因导致,所以一直想总结一下,形成一个良好的开发规范。 一、Unix时间戳 Unix时间戳(Unix timestamp),或称Unix时间(Unix time)、POSIX时间(...

java--枚举

前言   java中enum其实也是一种class类型,他和一般的class不同的是    1.全局只有一个实例    2.不能拥有public构造函数    3.无法继承和被继承 枚举案例 public enum HttpCode { SUCCESS(200, "操作成功"),//每定义一个枚举项,就相当通过构造函数HttpCode(int co...