OkHTTPClient
一,OKHttp介绍
okhttp是一个第三方类库,用于android中请求网络。
这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary) 。用于替代HttpUrlConnection和Apache HttpClient(android API23 里已移除HttpClient)。
okhttp有自己的官网,官网网址:OKHttp官网
如果想了解原码可以在github上下载,地址是:https://github.com/square/okhttp
在AndroidStudio、gradle中使用不需要下载jar包,直接添加依赖即可:
compile ‘com.squareup.okhttp3:okhttp:3.4.1’
项目中遇到的问题:
public JSONObject doPost(String url, JSONObject params,Boolean token,String type) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(JDCommonConstant.TIME_OUT, TimeUnit.SECONDS)
.readTimeout(JDCommonConstant.TIME_OUT, TimeUnit.SECONDS)
.build();
Set<String> iterator = null;
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
if(params != null) {
iterator = params.keySet();
for (String str : iterator) {
// log.info("当前参数::"+ str + " 类型:" + params.get(str).getClass());
String value = params.getString(str);
value=value.startsWith("\"")?value.substring(1,value.length()-1):value;
value=value.endsWith("\"")?value.substring(0,value.length()-1):value;
value=StringEscapeUtils.unescapeJava(value);
// log.info("当前参数的值::"+value +" 长度:"+ value.length());
builder.addFormDataPart(str, value);
}
}else {
builder.addFormDataPart("token", "");
}
RequestBody body = builder.build();
Request request = new Request.Builder()
.url(finalUrl)
.post(body)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
if(response.isSuccessful()) {
String str = response.body().string();
str=str.startsWith("\"")?str.substring(1,str.length()-1):str;
str=str.endsWith("\"")?str.substring(0,str.length()-1):str;
JSONObject object = JSON.parseObject(str);
log.info("接口返回值:"+ JSON.toJSONString(object));
return object;
}else {
//请求失败return null;
}
} catch (IOException e) {return null;
}
}
结果:无法访问,报错
解决:由于公司是内网,需要设置代理,增加代理
int proxyPort = 端口号8080;
String proxyHost = "代理host";
final String username = "";
final String password = "";
Authenticator proxyAuthenticator = new Authenticator() {
@Override public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(username, password);
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
} }; OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(JDCommonConstant.TIME_OUT, TimeUnit.SECONDS)
.readTimeout(JDCommonConstant.TIME_OUT, TimeUnit.SECONDS)
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)))
.proxyAuthenticator(proxyAuthenticator)
.build();
okhttp的使用详细介绍:https://blog.csdn.net/larryqingping/article/details/79440665
OkHTTPClient的更多相关文章
- okhttp封装时,提示 cannot resolve method OkHttpClient setConnectTimeout() 函数
如标题所示,okhttp封装时,提示 cannot resolve method OkHttpClient setConnectTimeout() 函数,有遇到这样现象的朋友吗? 原因:因使用的是 ...
- Android封装OkHttpClient的类库
由于android6.0的SDK没有HttpClient,只有HttpURLConnection和OkHttpClient,特记下OkHttpClient的使用方法 1.Ui测试界面布局 <?x ...
- OAthe2 Login use OkHttpClient and OAuth2RestTemplate
http://samchu.logdown.com/posts/1437422-oathe2-login-use-okhttpclient-and-oauth2resttemplate?utm_sou ...
- 使用OkHttpClient处理json请求处理的方式
今天遇到一个问题,重构老系统时,前端传递的参数是一个json,controller层可以用@ResponseBody来接收. 因为新系统用的是spring cloud这一套,调用其他服务使用的是fei ...
- Android Studio OkHttpClient使用
本次来记录下OkHttpClient的使用,OkHttpClient是用来完成android 客户端对服务端请求的工具. 首先记住,使用网络的时候一定要加入权限,加入到AndroidMainfest. ...
- OkHttpClient简单封装
一.接口 public interface HttpListener { void onFinish(String reponse); void onError(Exception e); } 二.O ...
- Okhttp3源码解析(1)-OkHttpClient分析
### 前言 上篇文章我们讲了[Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f),今天根据上节讲到请求流程来分析源码,那么第一步就是实例化OkH ...
- OkHttpClient调优案例
OkHttpClient调优案例 作者:Grey 原文地址: 语雀 博客园 Github 实际案例 系统运行一段时间后,线程数量飙升,CPU持续居高不下 排查工具 https://fastthread ...
- feign使用okHttpClient,调用原理
最近项目中 spring cloud 用到http请求,使用feign,配置okhttp,打算配置一下就直接使用,不过在压测与调优过程中遇到一些没有预测到的问题,附上排查与解析结 yml.pom配置 ...
随机推荐
- Python内置函数(17)——chr
英文文档: chr(i) Return the string representing a character whose Unicode code point is the integer i. F ...
- maven常见问题处理(3-2)maven打包时跳过测试的几个方法
运行mvn install时跳过Test方法一:<project> [...] <build> <plugins> <plugin> <group ...
- MySql查询正在进行中的事务
用法 SELECT * FROM information_schema.INNODB_TRX 这个只能查询此刻正在进行中的事务,已经完成的是查不到的 表字段定义 The INFORMATION_SCH ...
- 关于字数太多直接变成省略号的方法css
文字超出限制的宽度自动隐藏,并且变为省略号 这是之前写的,现在要做一个两行的 于是万能找百度,居然真的有这个方法: 于是,我就变成了搬运工:○( ^皿^)っHiahiahia- http://blog ...
- 【微信小程序】对微信http请求API的封装,方便对错误码进行处理
/** * App 微信配置文件app.js * author: nujey * versions: 1.0.0 */ App({ /** * @param {Object ...
- MongoDB系列六(聚合).
一.概念 使用聚合框架可以对集合中的文档进行变换和组合.基本上,可以用多个构件创建一个管道(pipeline),用于对一连串的文档进行处理.这些构件包括筛选(filtering).投射(project ...
- JavaScript数据结构与算法(三) 优先级队列的实现
TypeScript方式实现源码 // Queue类和PriorityQueue类实现上的区别是,要向PriorityQueue添加元素,需要创建一个特殊的元素.这个元素包含了要添加到队列的元素(它可 ...
- [LeetCode] Convert BST to Greater Tree 将二叉搜索树BST转为较大树
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original B ...
- 实战分享:如何成功防护1.2T国内已知最大流量DDoS攻击
作者:腾讯云宙斯盾安全团队&腾讯安全平台部 引言: DDoS攻击势头愈演愈烈,除了攻击手法的多样化发展之外,最直接的还是攻击流量的成倍增长.3月份国内的最大规模DDoS攻击纪录还停留在数百G规 ...
- snmp爆破(python脚本)
snmp用来获取信息,然后利用获取的信息来进一步的渗透. 命令行有 snmpwalk -v 2c -c public ip system -c是密码,默认的密码是public 利用工具可以找windo ...