okhttp3检测url
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class HttpUrlCode {
public static void main(String[] args) {
String url = "http://www.baidu.com";
System.out.println(HttpUrlCode.get(url));
}
private final static OkHttpClient okHttpClient;
static {
okHttpClient = new OkHttpClient.Builder().connectTimeout(5000, TimeUnit.SECONDS)
.readTimeout(5000, TimeUnit.SECONDS).build();
}
public static String get(String url) {
Request request = new Request.Builder().get().url(url).build();
Response response;
String code;
try {
response = okHttpClient.newCall(request).execute();
code = response.code() + "";
response.body().close();
} catch (IOException e) {
code = "404";
}
return code;
}
public static String post(String url, Map<String, String> map) {
String json = null;
FormBody.Builder builder = new FormBody.Builder();
Iterator<String> iterator = map.keySet().iterator();
String key, value;
while (iterator.hasNext()) {
key = iterator.next();
value = map.get(key);
if (!StringUtils.isNoneBlank(key, value)) {
builder.add(key, value);
}
}
FormBody dBody = builder.build();
Request request = new Request.Builder().post(dBody).url(url).build();
Response response;
try {
response = okHttpClient.newCall(request).execute();
json = response.body().string();
response.body().close();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
}