okhttp3的简单使用

一、引入依赖,如果不是maven项目直接引入对应jar包

      <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>3.6.0</version>
    </dependency>

注:如果引入的为旧版本com.squareup.okhttp,则有些语法会不一样

二、通过一个简单的例子实现okhttp的get/post方法

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class Okhttp3Demo
{
    //通过OKHttpClient发送一个简单的get请求百度首页
    public static void getDemo(){
        try{
            //创建okhttpclient对象,也可如下面的例子直接 new OkHttpClient()
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            //因为默认请求为get,所以 get() 可省略
            Request request = new Request.Builder().url("http://www.baidu.com").get().build();
            Response response = client.newCall(request).execute();
	    	if(response.isSuccessful()){
		    	ResponseBody responseBody = response.body();
                //打印出响应的内容,这里是百度的首页html内容
		    	System.out.println(responseBody.string());
	    	}
	    }catch(Exception e){
	    	e.printStackTrace();
	    }
	}
	
	//通过OKHttpClient发送一个简单的post请求
	public static void postDemo(){
		
		String path = "http://192.168.0.28/testPost";
        //创建okhttpclient对象
		OkHttpClient client = new OkHttpClient();
		
        //两种方式构建post请求体,携带对应的参数
        //RequestBody requestBody = new FormBody.Builder().add("name", "test").add("pwd", "12345").build();
		MediaType JSON = MediaType.parse("application/json; charset=utf-8");
		RequestBody requestBody = RequestBody.create(JSON, "{\"name\":\"test\",\"pwd\":\"12345\"}");
        //创建请求方式,可加 header(name,value) 设置请求头参数
        Request request = new Request.Builder().url(path).post(requestBody).build();
        //执行请求操作
        try {
            Response response = client.newCall(request).execute();
            if(response.isSuccessful()){
                String string = response.body().string();
                System.out.println(string);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}

 

另外我们可以通过HttpUrl类构建对应的url
HttpUrl url = new HttpUrl.Builder().scheme("http").host("www.baidu.com").addPathSegment("demo").addQueryParameter("one","value").build();
// 此时构建的url为 http://www.baidu.com/demo?one=value
再通过Request创建请求   
    Request request = new Request.Builder().url(url).build(); 

 

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值