java中的okhttp使用教程-亚博电竞手机版

目录

  • 什么是okhttp
  • okhttp基本使用
  • 添加依赖
  • okhttp工具类
  • 使用案例
    • 发送get请求
    • 发送post请求
    • 发送异步请求

什么是okhttp

一般在java平台上,我们会使用apache httpclient作为http客户端,用于发送 http 请求,并对响应进行处理。比如可以使用http客户端与第三方服务(如sso服务)进行集成,当然还可以爬取网上的数据等。okhttp与httpclient类似,也是一个http客户端,提供了对 http/2 和 spdy 的支持,并提供了连接池,gzip 压缩和 http 响应缓存功能;

okhttp是目前非常火的网络库,它有以下特性:

1.支持http/2,允许所有同一个主机地址的请求共享同一个socket连接

2.连接池减少请求延时

3.透明的gzip压缩减少响应数据的大小

4.缓存响应内容,避免一些完全重复的请求

okhttp基本使用

  • okhttpclient:客户端对象
  • request:访问请求,post请求中需要包含requestbody
  • requestbody:请求数据,在post请求中用到
  • response:即网络请求的响应结果
  • mediatype:数据类型,用来表明数据是jsonxhyigbe,image,pdf等一系列格式
  • client.newcall(request).execute():同步的请求方法
  • client.newcall(request).enqueue(callback callback):异步的请求方法,但callback是执行在子线程中的,因此不能在此进行ui更新操作

亚博电竞手机版官网:http://square.github.io/okhttp/

添加依赖

com.squareup.okhttp3 okhttp 3.10.0 com.alibaba fastjson 1.2.60恰卡编程网gt;

okhttp工具类

package com.loginsimpl.utils; import com.alibaba.fastjson.json; import okhttp3.*; import javax.net.ssl.sslcontext; import javax.net.ssl.sslsocketfactory; import javax.net.ssl.trustmanager; import javax.net.ssl.x509trustmanager; import java.io.ioexception; import java.net.urlencoder; import java.security.securerandom; import java.security.cert.x509certificate; import java.util.linkedhashmap; import java.util.map; import java.util.concurrent.semaphore; import java.util.concurrent.timeunit; public class okhttputils { private static volatile okhttpclient okhttpclient = null; private static volatile semaphore semaphore = null; private map headermap; private map parammap; private string url; private request.builder request; /** * 初始化okhttpclient,并且允许https访问 */ private okhttputils() { if (okhttpclient == null) { synchronized (okhttputils.class) { if (okhttpclient == null) { trustmanager[] trustmanagers = buildtrustmanagers(); okhttpclient = new okhttpclient.builder() .connecttimeout(15, timeunit.seconds) .writetimeout(20, timeunit.seconds) .readtimeout(20, timeunit.seconds) .sslsocketfactory(createsslsocketfactory(trustmanagers), (x509trustmanager) trustmanagers[0]) .hostnameverifier((hostname, session) -> true) .retryonconnectionfailure(true) .build(); addheader("user-agent", "mozilla/5.0 (macintosh; intel mac os x 10_12_6) applewebkit/537.36 (khtml, like gecko) chrome/63.0.3239.132 safari/537.36"); } } } } /** * 用于异步请求时,控制访问线程数www.cppcns.com,返回结果 * * @return */ private static semaphore getsemaphoreinstance() { //只能1个线程同时访问 synchronized (okhttputils.class) { if (semaphore == null) { semaphore = new semaphore(0); } } return semaphore; } /** * 创建okhttputils * * @return */ public static okhttputils builder() { return new okhttputils(); } /** * 添加url * * @param url * @return */ public okhttputils { this.url = url; return this; } /** * 添加参数 * * @param key 参数名 * @param value 参数值 * @return */ public okhttputils addparam(string key, string value) { if (parammap == null) { parammap = new linkedhashmap<>(16); } parammap.put(key, value); return this; } /** * 添加请求头 * * @param key 参数名 * @param value 参数值 * @return */ public okhttputils addheader(string key, string value) { if (headermap == null) { headermap = new linkedhashmap<>(16); } headermap.put(key, value); return this; } /** * 初始化get方法 * * @return */ public okhttputils get() { request = new request.builder().get(); stringbuilder urlbuilder = new stringbuilder(url); if (parammap != null) { urlbuilder.append("?"); try { for (map.entry entry : parammap.entryset()) { urlbuilder.append(urlencoder.encode(entry.getkey(), "utf-8")). append("="). append(urlencoder.encode(entry.getvalue(), "utf-8")). append("&"); } } catch (exception e) { e.printstacktrace(); } urlbuilder.deletecharat(urlbuilder.length() - 1); } request.); return this; } /** * 初始化post方法 * * @param isjsonpost true等于json的方式提交数据,类似postman里post方法的raw * false等于普通的表单提交 * @return */ public okhttputils post(boolean isjsonpost) { requestbody requestbody; if (isjsonpost) { string json = ""; if (parammap != null) { json = json.tojsonstring(parammap); } requestbody = requestbody.create(mediatype.parse("application/json; charset=utf-8"), json); } else { formbody.builder formbody = new formbody.builder(); if (parammap != null) { parammap.foreach(formbody::add); } requestbody = formbody.build(); } request = new request.builder().post(requestbody).; return this; } /** * 同步请求 * * @return */ public string sync() { setheader(request); try { response response = okhttpclient.newcall(request.build()).execute(); assert response.body() != null; return response.body().string(); } catch (ioexception e) { e.printstacktrace(); return "请求失败:" e.getmessage(); } } /** * 异步请求,有返回值 (限流的,同一时间只允许一个访问,其他等待) */ public string async() { stringbuilder buffer = new stringbuilder(""); setheader(request); okhttpclient.newcall(request.build()).enqueue(new callback() { @override public void onfailure(call call, ioexception e) { buffer.append("请求出错:").append(e.getmessage()); } @override public void onresponse(call call, response response) throws ioexception { assert response.body() != null; buffer.append(response.body().string()); getsemaphoreinstance().release(); } }); try { getsemaphoreinstance().acquire(); } catch (interruptedexception e) { e.printstacktrace(); } return buffer.tostring(); } /** * 异步请求,带有接口回调 * * @param callback */ public void async(icallback callback) { setheader(request); okhttpclient.newcall(request.build()).enqueue(new callback() { @override public void onfailure(call call, ioexception e) { callback.onfailure(call, e.getmessage()); } @override public void onresponse(call call, response response) throws ioexception { assert response.body() != null; callback.onsuccessful(call, response.body().string()); } }); } /** * 为request添加请求头 * * @param request */ private void setheader(request.builder request) { if (headermap != null) { try { for (map.entry entry : headermap.entryset()) { request.addheader(entry.getkey(), entry.getvalue()); } } catch (exception e) { e.printstacktrace(); } } } /** * 生成安全套接字工厂,用于https请求的证书跳过 * * @return */ private static sslsocketfactory createsslsocketfactory(trustmanager[] trustallcerts) { sslsocketfactory ssffactory = null; try { sslcontext sc = sslcontext.getinstance("ssl"); sc.init(null, trustallcerts, new securerandom()); ssffactory = sc.getsocketfactory(); } catch (exception e) { e.printstacktrace(); } return ssffactory; } private static trustmanager[] buildtrustmanagers() { return new trustmanager[]{ new x509trustmanager() { @override public void checkclienttrusted(x509certificate[] chain, string authtype) { } @override public void checkservertrusted(x509certificate[] chain, string authtype) { } @override public x509certificate[] getacceptedissuers() { return new x509certificate[]{}; } } }; } /** * 自定义一个接口回调 */ public interface icallback { void onsuccessful(call call, string data); void onfailure(call call, string errormsg); } }

使用案例

发送get请求

string sync = okhttputils.builder(). .addheader("token", "xxxxxxx") .addparam("name", "xxx").addparam("pass", "xxx") .get() .sync(); system.out.println(sync);

发送post请求

string sync = okhttputils.builder(). .addheader("token", "xxxxxxx") .addparam("name", "xxx").addparam("pass", "xxx") .post(true) // true 为json提交方式 .sync(); system.out.println(sync);

发送异步请求

需要实现icallback接口

//回调实现类 public class asynchttpserviceimpl implements okhttputils.icallback { @override public void onsuccessful(call call, string data) { //接口正常返回的内容 system.out.println("onsuccessful" data); } @override public void onfailure(call call, string errormsg) { //接口错误返回的内容 system.out.println("onfailure" errormsg); } }

发送异步请求

okhttputils.builder(). .addheader("token", "xxxxxxx") .addparam("name", "xxx").addparam("pass", "xxx") .post(true) .async(new asynchttpserviceimpl());

到此这篇关于java-okhttp使用教程的文章就介绍到这了,更多相关java-okhttp使用内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

展开全文
内容来源于互联网和用户投稿,文章中一旦含有亚博电竞手机版的联系方式务必识别真假,本站仅做信息展示不承担任何相关责任,如有侵权或涉及法律问题请联系亚博电竞手机版删除

最新文章

网站地图