OkHttpClient用例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mazaiting/article/details/78129542

Java OkHttp使用

本文使用eclipse编辑器,gradle依赖jar,如若未配置此环境,请转Java Eclipse配置gradle编译项目配置好环境后再查看此文

  1. 在build.gradle中添加依赖
    compile 'com.squareup.okhttp3:okhttp:3.8.1'
  2. 同步Get请求

      
      
  1. /**
  2. * 同步get请求
  3. */
  4. public static void syncGet() throws Exception{
  5. String urlBaidu = "http://www.baidu.com/";
  6. OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象
  7. Request request = new Request.Builder().url(urlBaidu).build(); // 创建一个请求
  8. Response response = okHttpClient.newCall(request).execute(); // 返回实体
  9. if (response.isSuccessful()) { // 判断是否成功
  10. /**获取返回的数据,可通过response.body().string()获取,默认返回的是utf-8格式;
  11. * string()适用于获取小数据信息,如果返回的数据超过1M,建议使用stream()获取返回的数据,
  12. * 因为string() 方法会将整个文档加载到内存中。*/
  13. System. out.println(response.body(). string()); // 打印数据
  14. } else {
  15. System. out.println( "失败"); // 链接失败
  16. }
  17. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  1. 异步Get请求

      
      
  1. /**
  2. * 异步Get请求
  3. */
  4. public static void asyncGet() {
  5. String urlBaidu = "http://www.baidu.com/";
  6. OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象
  7. Request request = new Request.Builder().url(urlBaidu).build(); // 创建一个请求
  8. okHttpClient.newCall(request).enqueue( new Callback() { // 回调
  9. public void onResponse(Call call, Response response) throws IOException {
  10. // 请求成功调用,该回调在子线程
  11. System. out.println(response.body(). string());
  12. }
  13. public void onFailure(Call call, IOException e) {
  14. // 请求失败调用
  15. System. out.println(e.getMessage());
  16. }
  17. });
  18. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

4.Post提交表单


      
      
  1. /**
  2. * Post提交表单
  3. */
  4. public static void postFromParameters() {
  5. String url = "http://v.juhe.cn/wepiao/query"; // 请求链接
  6. String KEY = "9488373060c8483a3ef6333353fdc7fe"; // 请求参数
  7. OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象
  8. RequestBody formBody = new FormBody.Builder(). add( "key", KEY).build(); // 表单键值对
  9. Request request = new Request.Builder().url(url).post(formBody).build(); // 请求
  10. okHttpClient.newCall(request).enqueue( new Callback() { // 回调
  11. public void onResponse(Call call, Response response) throws IOException {
  12. System. out.println(response.body(). string()); //成功后的回调
  13. }
  14. public void onFailure(Call call, IOException e) {
  15. System. out.println(e.getMessage()); //失败后的回调
  16. }
  17. });
  18. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  1. Post提交字符串

      
      
  1. /**
  2. * Post提交字符串
  3. * 使用Post方法发送一串字符串,但不建议发送超过1M的文本信息
  4. */
  5. public static void postStringParameters(){
  6. MediaType MEDIA_TYPE = MediaType.parse( "text/text; charset=utf-8");
  7. String url = "http://v.juhe.cn/wepiao/query"; // 请求链接
  8. OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象
  9. String string = "key=9488373060c8483a3ef6333353fdc7fe"; // 要发送的字符串
  10. /**
  11. * RequestBody.create(MEDIA_TYPE, string)
  12. * 第二个参数可以分别为:byte[],byteString,File,String。
  13. */
  14. Request request = new Request.Builder().url(url)
  15. .post(RequestBody.create(MEDIA_TYPE, string)).build();
  16. okHttpClient.newCall(request).enqueue( new Callback() {
  17. public void onResponse(Call call, Response response) throws IOException {
  18. System. out.println(response.body(). string());
  19. }
  20. public void onFailure(Call call, IOException e) {
  21. System. out.println(e.getMessage());
  22. }
  23. });
  24. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  1. Gson解析Response的Gson对象

      
      
  1. /**
  2. * Gson解析Response的Gson对象
  3. */
  4. public static void gsonResponsePost() {
  5. String url = "http://v.juhe.cn/wepiao/query"; // 请求链接
  6. String KEY = "9488373060c8483a3ef6333353fdc7fe"; // 请求参数
  7. OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象
  8. RequestBody formBody = new FormBody.Builder(). add( "key", KEY).build(); // 表单键值对
  9. Request request = new Request.Builder().url(url).post(formBody).build(); // 请求
  10. okHttpClient.newCall(request).enqueue( new Callback() { // 回调
  11. public void onResponse(Call call, Response response) throws IOException {
  12. //成功后的回调
  13. Gson gson = new Gson();
  14. Info info = gson.fromJson(response.body(). string(), Info.class);
  15. System. out.println(info.toString());
  16. }
  17. public void onFailure(Call call, IOException e) {
  18. System. out.println(e.getMessage()); //失败后的回调
  19. }
  20. });
  21. }
  22. /**
  23. * Java Bean
  24. */
  25. public class Info{
  26. int error_code; //状态码
  27. String reason; // 返回状态文字
  28. Result result; // 页面URL
  29. @ Override
  30. public String toString( ) {
  31. return "Info [error_code=" + error_code + ", reason=" + reason + ", result=" + result.toString() + "]";
  32. }
  33. }
  34. /**
  35. * Java Bean
  36. */
  37. public class Result{
  38. String h5url;
  39. String h5weixin;
  40. @ Override
  41. public String toString( ) {
  42. return "Result [h5url=" + h5url + ", h5weixin=" + h5weixin + "]";
  43. }
  44. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  1. okhttp3 设置超时时间

      
      
  1. /**
  2. * 设置超时
  3. * @throws IOException
  4. */
  5. public static void timeOutPost() throws IOException {
  6. OkHttpClient client = new OkHttpClient.Builder()
  7. .connectTimeout( 10, TimeUnit.SECONDS) //设置链接超时
  8. .writeTimeout( 10, TimeUnit.SECONDS) // 设置写数据超时
  9. .readTimeout( 30, TimeUnit.SECONDS) // 设置读数据超时
  10. .build();
  11. Request request = new Request.Builder().url( "http://www.baidu.com/").build();
  12. Response response = client.newCall(request).execute();
  13. System.out.println( "Response completed: " + response);
  14. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  1. 缓存设置

      
      
  1. /**
  2. * 缓存设置
  3. * @throws Exception
  4. */
  5. public static void cachePost() throws Exception {
  6. File sdcache = new File( "D:/file");
  7. int cacheSize = 10 * 1024 * 1024; // 10 MiB
  8. OkHttpClient client = new OkHttpClient()
  9. .Builder()
  10. .cache( new Cache(sdcache.getAbsoluteFile(), cacheSize))
  11. .build();
  12. Request request = new Request.Builder()
  13. .url( "http://publicobject.com/helloworld.txt")
  14. .build();
  15. Response response1 = client.newCall(request).execute();
  16. if (!response1.isSuccessful()) throw new IOException( "Unexpected code " + response1);
  17. String response1Body = response1.body(). string();
  18. System. out.println( "Response 1 response: " + response1);
  19. System. out.println( "Response 1 cache response: " + response1.cacheResponse());
  20. System. out.println( "Response 1 network response: " + response1.networkResponse());
  21. request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();
  22. Response response2 = client.newCall(request).execute();
  23. if (!response2.isSuccessful()) throw new IOException( "Unexpected code " + response2);
  24. String response2Body = response2.body(). string();
  25. System. out.println( "Response 2 response: " + response2);
  26. System. out.println( "Response 2 cache response: " + response2.cacheResponse());
  27. System. out.println( "Response 2 network response: " + response2.networkResponse());
  28. System. out.println( "Response 2 equals Response 1? " + response1Body. equals(response2Body));
  29. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

打印结果:


      
      
  1. Response 1 response: Response{protocol=http/ 1.1, code= 200, message=OK, url=https: //publicobject.com/helloworld.txt}
  2. Response 1 cache response: Response{protocol=http/ 1.1, code= 200, message=OK, url=https: //publicobject.com/helloworld.txt}
  3. Response 1 network response: null
  4. Response 2 response: Response{protocol=http/ 1.1, code= 200, message=OK, url=https: //publicobject.com/helloworld.txt}
  5. Response 2 cache response: null
  6. Response 2 network response: Response{protocol=http/ 1.1, code= 200, message=OK, url=https: //publicobject.com/helloworld.txt}
  7. Response 2 equals Response 1? true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. 复用OkHttpClient

      
      
  1. /**
  2. * 所有HTTP请求的代理设置,超时,缓存设置等都需要在OkHttpClient中设置。 如果需要更改一个请求的配置,可以使用
  3. * OkHttpClient.newBuilder()获取一个builder对象,
  4. * 该builder对象与原来OkHttpClient共享相同的连接池,配置等。
  5. */
  6. public static void shareClient() {
  7. OkHttpClient client = new OkHttpClient();
  8. Request request = new Request.Builder().url( "http://www.baidu.com/").build();
  9. try {
  10. // Copy to customize OkHttp for this request.
  11. OkHttpClient copy = client.newBuilder().readTimeout( 500, TimeUnit.MILLISECONDS).build();
  12. Response response = copy.newCall(request).execute();
  13. System. out.println( "Response 1 succeeded: " + response);
  14. } catch (IOException e) {
  15. System. out.println( "Response 1 failed: " + e);
  16. }
  17. try {
  18. // Copy to customize OkHttp for this request.
  19. OkHttpClient copy = client.newBuilder().readTimeout( 3000, TimeUnit.MILLISECONDS).build();
  20. Response response = copy.newCall(request).execute();
  21. System. out.println( "Response 2 succeeded: " + response);
  22. } catch (IOException e) {
  23. System. out.println( "Response 2 failed: " + e);
  24. }
  25. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  1. OkHttp3处理验证

      
      
  1. /**
  2. * 登录验证
  3. * @throws IOException
  4. */
  5. public static void authenticatorPost() throws IOException {
  6. OkHttpClient okHttpClient =
  7. new OkHttpClient
  8. .Builder()
  9. .authenticator( new Authenticator() {
  10. public Request authenticate(Route route, Response response) throws IOException {
  11. System.out.println( response.challenges().toString());
  12. String credential = Credentials.basic( "jesse", "password1");
  13. return response
  14. . request()
  15. .newBuilder()
  16. .addHeader( "Authorization", credential)
  17. .build();
  18. }
  19. })
  20. .build();
  21. Request request = new Request.Builder().url( "http://publicobject.com/secrets/hellosecret.txt").build();
  22. Response response = okHttpClient.newCall( request). execute();
  23. if (! response.isSuccessful()) throw new IOException( "Unexpected code " + response);
  24. System.out.println( response.body(). string());
  25. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

代码下载

    </div>
    <!--  --></div>            </div>
            </div>
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mazaiting/article/details/78129542

Java OkHttp使用

本文使用eclipse编辑器,gradle依赖jar,如若未配置此环境,请转Java Eclipse配置gradle编译项目配置好环境后再查看此文

  1. 在build.gradle中添加依赖
    compile 'com.squareup.okhttp3:okhttp:3.8.1'
  2. 同步Get请求

    
    
  1. /**
  2. * 同步get请求
  3. */
  4. public static void syncGet() throws Exception{
  5. String urlBaidu = "http://www.baidu.com/";
  6. OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象
  7. Request request = new Request.Builder().url(urlBaidu).build(); // 创建一个请求
  8. Response response = okHttpClient.newCall(request).execute(); // 返回实体
  9. if (response.isSuccessful()) { // 判断是否成功
  10. /**获取返回的数据,可通过response.body().string()获取,默认返回的是utf-8格式;
  11. * string()适用于获取小数据信息,如果返回的数据超过1M,建议使用stream()获取返回的数据,
  12. * 因为string() 方法会将整个文档加载到内存中。*/
  13. System. out.println(response.body(). string()); // 打印数据
  14. } else {
  15. System. out.println( "失败"); // 链接失败
  16. }
  17. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  1. 异步Get请求

    
    
  1. /**
  2. * 异步Get请求
  3. */
  4. public static void asyncGet() {
  5. String urlBaidu = "http://www.baidu.com/";
  6. OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象
  7. Request request = new Request.Builder().url(urlBaidu).build(); // 创建一个请求
  8. okHttpClient.newCall(request).enqueue( new Callback() { // 回调
  9. public void onResponse(Call call, Response response) throws IOException {
  10. // 请求成功调用,该回调在子线程
  11. System. out.println(response.body(). string());
  12. }
  13. public void onFailure(Call call, IOException e) {
  14. // 请求失败调用
  15. System. out.println(e.getMessage());
  16. }
  17. });
  18. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

4.Post提交表单


    
    
  1. /**
  2. * Post提交表单
  3. */
  4. public static void postFromParameters() {
  5. String url = "http://v.juhe.cn/wepiao/query"; // 请求链接
  6. String KEY = "9488373060c8483a3ef6333353fdc7fe"; // 请求参数
  7. OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象
  8. RequestBody formBody = new FormBody.Builder(). add( "key", KEY).build(); // 表单键值对
  9. Request request = new Request.Builder().url(url).post(formBody).build(); // 请求
  10. okHttpClient.newCall(request).enqueue( new Callback() { // 回调
  11. public void onResponse(Call call, Response response) throws IOException {
  12. System. out.println(response.body(). string()); //成功后的回调
  13. }
  14. public void onFailure(Call call, IOException e) {
  15. System. out.println(e.getMessage()); //失败后的回调
  16. }
  17. });
  18. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  1. Post提交字符串

    
    
  1. /**
  2. * Post提交字符串
  3. * 使用Post方法发送一串字符串,但不建议发送超过1M的文本信息
  4. */
  5. public static void postStringParameters(){
  6. MediaType MEDIA_TYPE = MediaType.parse( "text/text; charset=utf-8");
  7. String url = "http://v.juhe.cn/wepiao/query"; // 请求链接
  8. OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象
  9. String string = "key=9488373060c8483a3ef6333353fdc7fe"; // 要发送的字符串
  10. /**
  11. * RequestBody.create(MEDIA_TYPE, string)
  12. * 第二个参数可以分别为:byte[],byteString,File,String。
  13. */
  14. Request request = new Request.Builder().url(url)
  15. .post(RequestBody.create(MEDIA_TYPE, string)).build();
  16. okHttpClient.newCall(request).enqueue( new Callback() {
  17. public void onResponse(Call call, Response response) throws IOException {
  18. System. out.println(response.body(). string());
  19. }
  20. public void onFailure(Call call, IOException e) {
  21. System. out.println(e.getMessage());
  22. }
  23. });
  24. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  1. Gson解析Response的Gson对象

    
    
  1. /**
  2. * Gson解析Response的Gson对象
  3. */
  4. public static void gsonResponsePost() {
  5. String url = "http://v.juhe.cn/wepiao/query"; // 请求链接
  6. String KEY = "9488373060c8483a3ef6333353fdc7fe"; // 请求参数
  7. OkHttpClient okHttpClient = new OkHttpClient(); // OkHttpClient对象
  8. RequestBody formBody = new FormBody.Builder(). add( "key", KEY).build(); // 表单键值对
  9. Request request = new Request.Builder().url(url).post(formBody).build(); // 请求
  10. okHttpClient.newCall(request).enqueue( new Callback() { // 回调
  11. public void onResponse(Call call, Response response) throws IOException {
  12. //成功后的回调
  13. Gson gson = new Gson();
  14. Info info = gson.fromJson(response.body(). string(), Info.class);
  15. System. out.println(info.toString());
  16. }
  17. public void onFailure(Call call, IOException e) {
  18. System. out.println(e.getMessage()); //失败后的回调
  19. }
  20. });
  21. }
  22. /**
  23. * Java Bean
  24. */
  25. public class Info{
  26. int error_code; //状态码
  27. String reason; // 返回状态文字
  28. Result result; // 页面URL
  29. @ Override
  30. public String toString( ) {
  31. return "Info [error_code=" + error_code + ", reason=" + reason + ", result=" + result.toString() + "]";
  32. }
  33. }
  34. /**
  35. * Java Bean
  36. */
  37. public class Result{
  38. String h5url;
  39. String h5weixin;
  40. @ Override
  41. public String toString( ) {
  42. return "Result [h5url=" + h5url + ", h5weixin=" + h5weixin + "]";
  43. }
  44. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  1. okhttp3 设置超时时间

    
    
  1. /**
  2. * 设置超时
  3. * @throws IOException
  4. */
  5. public static void timeOutPost() throws IOException {
  6. OkHttpClient client = new OkHttpClient.Builder()
  7. .connectTimeout( 10, TimeUnit.SECONDS) //设置链接超时
  8. .writeTimeout( 10, TimeUnit.SECONDS) // 设置写数据超时
  9. .readTimeout( 30, TimeUnit.SECONDS) // 设置读数据超时
  10. .build();
  11. Request request = new Request.Builder().url( "http://www.baidu.com/").build();
  12. Response response = client.newCall(request).execute();
  13. System.out.println( "Response completed: " + response);
  14. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  1. 缓存设置

    
    
  1. /**
  2. * 缓存设置
  3. * @throws Exception
  4. */
  5. public static void cachePost() throws Exception {
  6. File sdcache = new File( "D:/file");
  7. int cacheSize = 10 * 1024 * 1024; // 10 MiB
  8. OkHttpClient client = new OkHttpClient()
  9. .Builder()
  10. .cache( new Cache(sdcache.getAbsoluteFile(), cacheSize))
  11. .build();
  12. Request request = new Request.Builder()
  13. .url( "http://publicobject.com/helloworld.txt")
  14. .build();
  15. Response response1 = client.newCall(request).execute();
  16. if (!response1.isSuccessful()) throw new IOException( "Unexpected code " + response1);
  17. String response1Body = response1.body(). string();
  18. System. out.println( "Response 1 response: " + response1);
  19. System. out.println( "Response 1 cache response: " + response1.cacheResponse());
  20. System. out.println( "Response 1 network response: " + response1.networkResponse());
  21. request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();
  22. Response response2 = client.newCall(request).execute();
  23. if (!response2.isSuccessful()) throw new IOException( "Unexpected code " + response2);
  24. String response2Body = response2.body(). string();
  25. System. out.println( "Response 2 response: " + response2);
  26. System. out.println( "Response 2 cache response: " + response2.cacheResponse());
  27. System. out.println( "Response 2 network response: " + response2.networkResponse());
  28. System. out.println( "Response 2 equals Response 1? " + response1Body. equals(response2Body));
  29. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

打印结果:


    
    
  1. Response 1 response: Response{protocol=http/ 1.1, code= 200, message=OK, url=https: //publicobject.com/helloworld.txt}
  2. Response 1 cache response: Response{protocol=http/ 1.1, code= 200, message=OK, url=https: //publicobject.com/helloworld.txt}
  3. Response 1 network response: null
  4. Response 2 response: Response{protocol=http/ 1.1, code= 200, message=OK, url=https: //publicobject.com/helloworld.txt}
  5. Response 2 cache response: null
  6. Response 2 network response: Response{protocol=http/ 1.1, code= 200, message=OK, url=https: //publicobject.com/helloworld.txt}
  7. Response 2 equals Response 1? true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. 复用OkHttpClient

    
    
  1. /**
  2. * 所有HTTP请求的代理设置,超时,缓存设置等都需要在OkHttpClient中设置。 如果需要更改一个请求的配置,可以使用
  3. * OkHttpClient.newBuilder()获取一个builder对象,
  4. * 该builder对象与原来OkHttpClient共享相同的连接池,配置等。
  5. */
  6. public static void shareClient() {
  7. OkHttpClient client = new OkHttpClient();
  8. Request request = new Request.Builder().url( "http://www.baidu.com/").build();
  9. try {
  10. // Copy to customize OkHttp for this request.
  11. OkHttpClient copy = client.newBuilder().readTimeout( 500, TimeUnit.MILLISECONDS).build();
  12. Response response = copy.newCall(request).execute();
  13. System. out.println( "Response 1 succeeded: " + response);
  14. } catch (IOException e) {
  15. System. out.println( "Response 1 failed: " + e);
  16. }
  17. try {
  18. // Copy to customize OkHttp for this request.
  19. OkHttpClient copy = client.newBuilder().readTimeout( 3000, TimeUnit.MILLISECONDS).build();
  20. Response response = copy.newCall(request).execute();
  21. System. out.println( "Response 2 succeeded: " + response);
  22. } catch (IOException e) {
  23. System. out.println( "Response 2 failed: " + e);
  24. }
  25. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  1. OkHttp3处理验证

    
    
  1. /**
  2. * 登录验证
  3. * @throws IOException
  4. */
  5. public static void authenticatorPost() throws IOException {
  6. OkHttpClient okHttpClient =
  7. new OkHttpClient
  8. .Builder()
  9. .authenticator( new Authenticator() {
  10. public Request authenticate(Route route, Response response) throws IOException {
  11. System.out.println( response.challenges().toString());
  12. String credential = Credentials.basic( "jesse", "password1");
  13. return response
  14. . request()
  15. .newBuilder()
  16. .addHeader( "Authorization", credential)
  17. .build();
  18. }
  19. })
  20. .build();
  21. Request request = new Request.Builder().url( "http://publicobject.com/secrets/hellosecret.txt").build();
  22. Response response = okHttpClient.newCall( request). execute();
  23. if (! response.isSuccessful()) throw new IOException( "Unexpected code " + response);
  24. System.out.println( response.body(). string());
  25. }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

代码下载

    </div>
    <!--  --></div>            </div>
            </div>

猜你喜欢

转载自blog.csdn.net/Vazzz/article/details/84099982