package demo;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* 获取微信服务器ip
* @author pxh
*2016-12-07
*/
public class GetServiceIp {
private static String urlPath = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=";
private static String token = 令牌;
public static String getIps(){
String ips = null;
try {
URL url = new URL(urlPath+token);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置链接超时时间
connection.setConnectTimeout(30*1000);
//设置读取超时时间
connection.setReadTimeout(30*1000);
//设置请求方式
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
InputStream is = connection.getInputStream();
int size = is.available();
byte[] message = new byte[size];
is.read(message);
ips = new String(message,"UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return ips;
}
public static void main(String[] args) {
String ipJson = GetServiceIp.getIps();
System.out.println("微信服务器ip:"+ipJson);
List<String> listIps = new ArrayList<String>();
/**
* 使用gosn解析json
*/
JsonObject jsonObject = new JsonParser().parse(ipJson).getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("ip_list");
Gson gson = new Gson();
for(JsonElement element : jsonArray){
String ip = gson.fromJson(element, String.class);
if(null != ip && !"".equals(ip) && ip.contains("/")){ //"58.251.80.32\/27" 因为微信获取的ip中有这种格式的数据所以进行了如下处理
int startindex =ip.indexOf("/");
listIps.add(ip.substring(0,startindex));
listIps.add(ip.substring(0,ip.lastIndexOf(".")+1)+ip.substring(startindex+1));
}else{
listIps.add(ip);
}
}
}
}