OkHttpClient

2017-08-25  本文已影响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();
        }
    }
}

上一篇 下一篇

猜你喜欢

热点阅读