1.测试服务器端口是否可达
public boolean isHostConnectable(String host,int port){
Socke socket = new Socket();
try{
socket.connect(new InetSocketAddress(host,port),timeOut);//在指定超时时间内尝试连接
}catch(IOException e){
return false;
}finally{
try{
socket.close();
}catch(IOException e){
}
}
return true;
}
附:不靠谱的 isReachable
try{
InetAddress ad = InetAddress.getByName(host);
return ad.isReachable(1000);//isReachable不靠谱:测试1000毫秒内false,socket.connect耗时只13毫秒
}catch(UnknownHostException e){
}catch(IOException e){
}
2.从多个服务器中选择连接较优的(设计思路:连接耗时越短越优)
//返回单个服务器端口连接时长
public long preHandler(String url,int port){
long curNanoTime = System.nanoTime() - ;
long curMilTime = System.currentTimeMillis();
isHostConnectable(url,port);
long intervalN = System.nanoTime() - curNanoTime;//纳秒
long intervalM = System.currentTimeMillis() - curMilTime;//毫秒
return intervalM;
}
//选择较优
public String[] choose(){
String[] hosts = hostString.split(",");//hostString为自定义的多个服务器ip字符串
long[] intervals = new long[hosts.length];
int i = 0;
for(String host : hosts){
intervals[i] = preHandler(host,port);//计算每个服务端口的连接时长
i++;
}
//冒泡排序,起始最优
for(int j = 1; j < intervals.length; j++){
for(int k = 0; k < intervals.length - j; k++){
if(intervals[k] > intervals[k + 1]){
String temp = hosts[k];
hosts[k] = hosts[k + 1];
hosts[k + 1] = temp;
}
}
}
return hosts;
}
3.执行http请求
Strng url = "http://192.168.1.10:8080/aaa";
String charset = "utf-8";
String JSONString = JSON.toJSONString(objectBean);//objectBean为对象bean
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
StringEntity entity = new StrngEntity(JSONString,charset);//乱码
entity.setContentEncoding(charset);
entity.setContentType("applicaiton/json");
httpPost.setEntity(entity);
HttpResponse resp = null;
try{
resp = client.execute(httpPost);
}catch(exception e){
}
if(resp !=null && resp.getStatusLine().getStatusCode() == 200){
//成功
}