一,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的更多相关文章

  1. okhttp封装时,提示 cannot resolve method OkHttpClient setConnectTimeout() 函数

    如标题所示,okhttp封装时,提示 cannot resolve method  OkHttpClient setConnectTimeout() 函数,有遇到这样现象的朋友吗? 原因:因使用的是 ...

  2. Android封装OkHttpClient的类库

    由于android6.0的SDK没有HttpClient,只有HttpURLConnection和OkHttpClient,特记下OkHttpClient的使用方法 1.Ui测试界面布局 <?x ...

  3. OAthe2 Login use OkHttpClient and OAuth2RestTemplate

    http://samchu.logdown.com/posts/1437422-oathe2-login-use-okhttpclient-and-oauth2resttemplate?utm_sou ...

  4. 使用OkHttpClient处理json请求处理的方式

    今天遇到一个问题,重构老系统时,前端传递的参数是一个json,controller层可以用@ResponseBody来接收. 因为新系统用的是spring cloud这一套,调用其他服务使用的是fei ...

  5. Android Studio OkHttpClient使用

    本次来记录下OkHttpClient的使用,OkHttpClient是用来完成android 客户端对服务端请求的工具. 首先记住,使用网络的时候一定要加入权限,加入到AndroidMainfest. ...

  6. OkHttpClient简单封装

    一.接口 public interface HttpListener { void onFinish(String reponse); void onError(Exception e); } 二.O ...

  7. Okhttp3源码解析(1)-OkHttpClient分析

    ### 前言 上篇文章我们讲了[Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f),今天根据上节讲到请求流程来分析源码,那么第一步就是实例化OkH ...

  8. OkHttpClient调优案例

    OkHttpClient调优案例 作者:Grey 原文地址: 语雀 博客园 Github 实际案例 系统运行一段时间后,线程数量飙升,CPU持续居高不下 排查工具 https://fastthread ...

  9. feign使用okHttpClient,调用原理

    最近项目中 spring cloud 用到http请求,使用feign,配置okhttp,打算配置一下就直接使用,不过在压测与调优过程中遇到一些没有预测到的问题,附上排查与解析结 yml.pom配置 ...

随机推荐

  1. linux下的Shell编程(4)特殊的变量和占位符

    $#表示包括$0在内的命令行参数的个数.在Shell中,脚本名称本身是$0,剩下的依次是$0.$1.$2-.${9},等等. $*表示整个参数列表,不包括$0,也就是说不包括文件名的参数列表. $?表 ...

  2. React-redux使用中有关Provider问题

    先上错误: Warning: Failed prop type: Invalid prop `children` of type `array` supplied to `Provider`, exp ...

  3. POJ-2184 Cow Exhibition---01背包变形(负数偏移)

    题目链接: https://vjudge.net/problem/POJ-2184 题目大意: 给出num(num<=100)头奶牛的S和F值(-1000<=S,F<=1000),要 ...

  4. python自带的web服务器

    python自带的web服务器 python自带的包可以建立简单的web服务器 BaseHTTPServer 提供基本的web服务和处理类 SimpleHTTPServer 包含执行get请求的Sim ...

  5. selenium用法详解

    selenium用法详解 selenium主要是用来做自动化测试,支持多种浏览器,爬虫中主要用来解决JavaScript渲染问题. 模拟浏览器进行网页加载,当requests,urllib无法正常获取 ...

  6. CLR-基元类型以及溢出检查

    =========(CLR via C#阅读笔记)======== 基元类型(primitive type): 基元类型也不做过多的解释,举个例子即可清晰的辨别 在java里曾使用过Sting s=& ...

  7. 关于oracle11g在window10环境下安装不满足最低要求问题:报错NS-13001

    安装oracle11g时遇到INS-13001环境不满足最低要求: oracle在安装前会自动检测电脑配置,主要是内存的满足,但是博主最近在window10上装oracle11g时,发生了不满足最低要 ...

  8. eclipse下maven插件搭建springmvc之helloworld

    这几天学习了怎样使用maven,最终还是要回归web项目嘛,所以主要还是使用eclipse插件. 1 下载eclipse maven插件. 其实新版的eclipse已经集成了maven:lunar.m ...

  9. springmvc文件下载之文件名下划线问题终极解决方案

    直接上代码:Action中代码片段. @RequestMapping("download")public String download(ModelMap model, @Mode ...

  10. win10配置Memcached及MVC5测试分布式缓存入门

    win10配置Memcached: 1.安装包下载 2.解压后有: 3.以管理员省份运行cmd: 4.安装:输入cmd命令: E:/memcached-amd64/memcached.exe -d  ...