今天我们就讲一下okhttp的使用,具体的okhttp使用可以参见官方的文档。

okhttp的使用

一、okhttp的下载安装

  • Download the latest JAR or grab via Maven:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.5.0</version>
</dependency>
  • 或者使用Gradle:在build.properties的dependencies下添加:
compile 'com.squareup.okhttp3:okhttp:3.5.0'

二、okHttp的基础使用

  • get的同步请求:The string() method on response body is convenient and efficient for small documents. But if the response body is large (greater than 1 MiB), avoid string() because it will load the entire document into memory. In that case, prefer to process the body as a stream.
@Test
public void okHttpTest1() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://localhost:8080/TomcatClient/ParameterServlet").build();
try {
Response response = client.newCall(request).execute();
ResponseBody body = response.body();
String string = body.string();
System.out.println("string " + string);
body.close();
} catch (IOException e) {
e.printStackTrace();
}
}
  • get的异步请求:Download a file on a worker thread, and get called back when the response is readable. The callback is made after the response headers are ready. Reading the response body may still block. OkHttp doesn't currently offer asynchronous APIs to receive a response body in parts.
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://localhost:9999/huhx1.json").build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("hello wrold fail");
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
} @Override
public void onFailure(Call call, IOException exception) {
exception.printStackTrace();
}
});
  • post请求
@Test
public void okHttpTest3() {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder().add("username", "huhx").add("password", "123456").build();
Request request = new Request.Builder().url("http://localhost:8080/TomcatClient/ParameterServlet").post(formBody).build();
try {
Response response = client.newCall(request).execute();
ResponseBody body = response.body();
String string = body.string();
System.out.println("string " + string);
body.close();
} catch (IOException e) {
e.printStackTrace();
}
}
  • json格式的post请求
@Test
public void okHttpTest4() {
MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
json.put("username", "huhx");
json.put("password", "123456");
RequestBody requestBody = RequestBody.create(JSON_TYPE, json.toJSONString());
Request request = new Request.Builder().url("http://localhost:8080/TomcatClient/JsonRequestServlet").post(requestBody).build();
try {
Response response = client.newCall(request).execute();
ResponseBody body = response.body();
String string = body.string();
System.out.println("string " + string);
body.close();
} catch (IOException e) {
e.printStackTrace();
}
}

友情链接

web基础---->okhttp的使用的更多相关文章

  1. Golang友团无闻Go语言Web基础视频教程

    教程内容:GO语言资料Golang友团无闻Go语言编程基础Golang友团无闻Go语言Web基础教程 Go语言Web基础教程列表:[Go Web基础]12Go Web 扩展学习.mp4[Go Web基 ...

  2. HT for Web基础动画介绍

    在上一篇<基于HT for Web矢量实现3D叶轮旋转>一文中,我略微提了下HT for Web基础动画的相关用法,但是讲得不深入,今天就来和大家分享下HT for Web基础动画的相关介 ...

  3. Web基础开发最核心要解决的问题

    Web基础开发要解决的问题,往往也就是那些框架出现的目的 - 要解决问题. 1. 便捷的Db操作: 2. 高效的表单处理: 3. 灵活的Url路由: 4. 合理的代码组织结构: 5. 架构延伸 缓存. ...

  4. web基础--html

    WebBasic 1.web应用体系 课程大纲 1.web基础:做网页     2.结构:         a.html             勾勒网页结构及内容         b.css     ...

  5. java web基础环境搭建

    java web基础环境包括:(1)servlet容器也即tomcat(2)jre即java程序运行环境 环境变量配置:分别下载jdk和tomcat安装包. jdk环境变量配置: 第一步:系统环境变量 ...

  6. Web基础知识和技术

    WEB是一个外延广泛的概念,不单单指网站,乌徒帮专注拥有WEB界面的网站开发,帮助初学者或已经进入开发的朋友们提供参考讨论平台,然而并不一定能将所有的WEB知识讲全讲透,只是能满足初涉者的建站需求,能 ...

  7. java web基础 --- URL重定向Filter

    java web基础 --- URL重定向Filter httpRequest.getRequestDispatcher("/helloWorld").forward(httpRe ...

  8. (0)写给Web初学者的教案-----Web基础

    0,Web基础 一.    What is the Web? Can It Eat? 很多同学可能都听说过一个名词叫做“Web”,这个词隐隐约约好像和我们上网相关.但是呢,又很难说的清楚.我们今天每位 ...

  9. web基础系列(五)---https是如何实现安全通信的

    https是如何实现安全通信的 如果有不正确的地方,还望指出! web基础系列目录 总结几种常见web攻击手段极其防御方式 总结几种常见的安全算法 回顾 总结几个概念(具体描述可以看上一篇文章) 数字 ...

随机推荐

  1. TCPdump抓包命令详解

    http://starsliao.blog.163.com/blog/static/89048201062333032563/ TCPdump抓包命令 tcpdump是一个用于截取网络分组,并输出分组 ...

  2. libtommath.a: could not read symbols: Bad value 编译错误

    最近做个项目需要RSA,便调用了tommath,平时开发环境都在32位的系统上,编译运行一切都没问题,但当把程序换到一台64位系统上编译时出现: /usr/bin/ld: /usr/lib/gcc/x ...

  3. 字符数组在C++、C#等语言中的操作

    1.C++中操作数组 #include <iostream> using namespace std; int length(char []); void output_frequency ...

  4. Java-jdbc连接简化类jdbcUtil

    在src文件夹下创建配置文件 db.properties db.properties drivername=com.mysql.jdbc.Driver url=jdbc:mysql://localho ...

  5. JS中的数字比较

    if(parseInt(current_index)!=parseInt(uls)){

  6. 超多的CSS3圆角渐变网页按钮

    <!DOCTYPE html><head><title>超多的CSS3圆角渐变按钮</title><style type="text/c ...

  7. Asp.Net MVC EasyUI DataGrid查询分页

    function doSearch() { //查询方法 var searchValue = $('#txtQueryTC001').textbox('getText'); $('#dgCMSTC') ...

  8. imx6 电容屏参数更改

    imx6使用电容屏时需要获取对应的usb的event.其中用到了shell的一些命令.分析如下. # inputCheckLine=`cat /proc/bus/input/devices | gre ...

  9. ubuntu12.04开启虚拟机的unity模式

    终端中输入: sudo add-apt-repository ppa:gnome3-team/gnome3 sudo apt-get update sudo apt-get install gnome ...

  10. 第二百八十六节,MySQL数据库-MySQL事务操作(回滚)

    MySQL数据库-MySQL事务操作(回滚) 事务用于将某些操作的多个SQL作为原子性操作,一旦有某一个出现错误,即可回滚到原来的状态,从而保证数据库数据完整性. 举例:有这样一张表 从表里可以看出张 ...