美文网首页
OkHttpClient

OkHttpClient

作者: 安安静静写代码 | 来源:发表于2017-08-25 16:51 被阅读22次

GET请求方式(默认)

package com.qf.demo7;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Test {

    public static void main(String[] args) {
        String path="http://localhost:8080/Day28_03/LoginServlet?useName=zhangsan&pwd=123";
        // 1 创建okhttp客户端对象
        OkHttpClient client  = new OkHttpClient();
        // 2 request 默认是get请求
        Request request = new  Request.Builder().url(path).build();
        // 3 进行请求操作
        try {
            Response response = client.newCall(request).execute();
            // 4 判断是否请求成功
            if(response.isSuccessful()){
                // 得到响应体中的身体,将其转成  string
                String string = response.body().string();
                System.out.println(string);
            }
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }
}

POST请求方式


package com.qf.demo7;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Test3 {

    public static void main(String[] args) {
        String path = "http://localhost:8080/Day28_03/LoginServlet";
        
        // 2 创建okhttpclient对象
        OkHttpClient client = new OkHttpClient();
        
        RequestBody body = new FormBody.Builder().add("useName", "addd").add("pwd", "123").build();
        // 3 创建请求方式
        Request request = new Request.Builder().url(path).post(body).build();
        
        // 4 执行请求操作
        try {
            Response response = client.newCall(request).execute();
            if(response.isSuccessful()){
                String string = response.body().string();
                System.out.println(string);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

相关文章

网友评论

      本文标题:OkHttpClient

      本文链接:https://www.haomeiwen.com/subject/idtpdxtx.html