最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Mac的Java中使用OkHttp去进行基本的网络请求

Mac crifan 652浏览 0评论
折腾:
【未解决】用Java实现百度模拟登陆
期间,Mac中已经搭建好了Java的IntelliJ IDEA的开发环境。
然后也基本上搞清楚,OkHttp是好用的Java的网络库。
那现在就是去看看如何使用。
OkHttp
http://square.github.io/okhttp/
看了demo代码
去下载jar
http://repo1.maven.org/maven2/com/squareup/okhttp3/okhttp/3.11.0/okhttp-3.11.0.jar
然后去看看如何导入到IntelliJ中
【已解决】IntelliJ IDEA中导入java的jar包OkHttp库文件
然后可以看到各种类:
双击去看看:
然后就下载下来了:
然后看看如何调用OkHttp去访问网络。
结果报错:
【已解决】java中调用OkHttp出错:Exception in thread “main” java.lang.NoClassDefFoundError: okio/BufferedSource
然后就解决了该问题了,不过又出现其他的:
【已解决】java中调用OkHttp出错:Exception in thread “main” java.lang.NoClassDefFoundError: kotlin/TypeCastException
然后就可以正常获取url返回的信息,包括response了:
【总结】
此处是用:
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class EmulateLoginBaidu {
    OkHttpClient client = new OkHttpClient();

//    ResponseBody run(String url) throws IOException {
    Response run(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

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

    public static void main(String[] args) throws IOException {
        System.out.println("Try Emulate Login Baidu");

        String baiduUrl = "http://www.baidu.com";

        EmulateLoginBaidu emulateLogin = new EmulateLoginBaidu();
//        ResponseBody respBody = emulateLogin.run(baiduUrl);
        Response response = emulateLogin.run(baiduUrl);
        System.out.println("response=" + response);
    }
}
其中要导入
  • okio-2.1.0.jar
和:
  • kotlin-stdlib.jar
  • kotlin-stdlib-common.jar
然后才能正常运行,即可获取url的Response了。

转载请注明:在路上 » 【已解决】Mac的Java中使用OkHttp去进行基本的网络请求

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
92 queries in 0.183 seconds, using 23.34MB memory