网络访问的HTTP、TCP/IP、UDP协议详解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/meiwei_1/article/details/53308368







OkHttp的使用

static class RequestThread implements Runnable{
private String requestPath;
public RequestThread(String requestPath){
this.requestPath = requestPath;
}

@Override
public void run() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build() ;
StrictMode. setThreadPolicy (policy) ;

//1.创建OkHttp请求客户端
OkHttpClient client = new OkHttpClient();
//2.创建请求构造者对象
Builder builder = new Builder();
//2.1 指定请求路径
builder.url(path);
//2.2 指定请求方式
builder.get();
//3.通过构建者Builder对象创建Http请求对象
Request request = builder.build();
try {
//4.Call 客户端将请求对象封装成任务(Call),再执行请求动作,并获取响应对象
Response response = client.newCall(request).execute();
//5.判断响应是否成功
if(response.isSuccessful()){
//6.获取响应体
ResponseBody body = response.body();
//获取数据
String result = body.string();
System.out.println(result);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}















//获取本地主机
InetAddress ia = InetAddress.getLocalHost();
System.out.println("主机名:"+ia.getHostName()+" 主机地址:"+ia.getHostAddress());
//获取网络主机
InetAddress ia1 = InetAddress.getByName("www.baidu.com");
System.out.println("百度主机名:"+ia1.getHostName()+" 百度主机地址:"+ia1.getHostAddress());

//获取局域网主机 如果拿不到主机名,通常返回Ip地址
InetAddress ia2 = InetAddress.getByName("10.10.159.22");
System.out.println("局域网主机名:"+ia2.getHostName()+" 局域网主机地址:"+ia2.getHostAddress());

InetAddress[] ias = InetAddress.getAllByName("www.163.com");
//一个域名可以对应多个Ip(比如一台主机挂了,另一台也可以正常运行),但是一个Ip只能对应一个域名
for(InetAddress ia3:ias){
System.out.println("163主机名:"+ia3.getHostName()+" 163主机地址:"+ia3.getHostAddress());
}




猜你喜欢

转载自blog.csdn.net/meiwei_1/article/details/53308368