OkHttp快速入门

OkHttp快速入门

有时间了再详细介绍,直接上代码

一. 具体操作

1.1 具体操作

  1. 引入依赖 在Maven 项目中pom.xml中引入依赖
		<!-- OKHttp3依赖 -->
		<dependency>
			<groupId>com.squareup.okhttp3</groupId>
			<artifactId>okhttp</artifactId>
			<version>3.8.1</version>
		</dependency>
  1. 封装类 OkHttpRequest.java
package com.cdmtc.remote;

import okhttp3.*;

import java.io.IOException;

/**
 * @create_by: 暗余
 * @craete_time 2019/6/24
 */
public class OkHttpRequest {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();
    public String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
    /*  Call call = client.newCall(request);
      call.*/

        Response response = client.newCall(request).execute();
        return response.body().string();
    }
}
  1. 请求其他接口:
package com.xxl.job.core.util;


/**
 * @create_by: anyu
 * @craete_time 2019/7/1
 */
public class Test {

    public static void main(String[] args) {


        try {
            OkHttpRequest okHttpRequest = new OkHttpRequest();
            String url = "https://blog.csdn.net/qq_37128049/article/details/93890588";
            String s = okHttpRequest.get(url);
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
发布了127 篇原创文章 · 获赞 52 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_37128049/article/details/93890588