折腾:
【未解决】用Java实现百度模拟登陆
期间,Mac中已经搭建好了Java的IntelliJ IDEA的开发环境。
然后也基本上搞清楚,OkHttp是好用的Java的网络库。
那现在就是去看看如何使用。
OkHttp
看了demo代码
去下载jar
![](https://www.crifan.com/files/pic/uploads/2021/05/7757d77aa3b54bd78fd21f9d50d5c6c7.jpg)
然后去看看如何导入到IntelliJ中
【已解决】IntelliJ IDEA中导入java的jar包OkHttp库文件
然后可以看到各种类:
![](https://www.crifan.com/files/pic/uploads/2021/05/a33d719cf46f4afd94e724c961d95b73.jpg)
双击去看看:
![](https://www.crifan.com/files/pic/uploads/2021/05/01e43f6eb7d14de88771d8958c30604a.jpg)
![](https://www.crifan.com/files/pic/uploads/2021/05/10bcc447e88a4f5cb9195625d1ba7c1a.jpg)
![](https://www.crifan.com/files/pic/uploads/2021/05/4ad40d559916461a8ea32f0a8891ff8e.jpg)
![](https://www.crifan.com/files/pic/uploads/2021/05/3cd1b08a44ea4049b7643df00da88be1.jpg)
然后就下载下来了:
![](https://www.crifan.com/files/pic/uploads/2021/05/3eb3f8e9ab56422184ec8d13d10936dc.jpg)
然后看看如何调用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了:
![](https://www.crifan.com/files/pic/uploads/2021/05/1b3cb9f1ecbd4ae1ac12d917773f8b05.jpg)
【总结】
此处是用:
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去进行基本的网络请求