股票场内基金交易,没时间盯盘?
引言
OkHttp作为时下最火的http框架,以它的轻量级、高效率的优势,深受广大开发者的喜爱,使用它的人越来越多。说到这我就比较惭愧了,因为我最近才开始学习OkHttp,经过一番学习,掌握了OkHttp的基本使用,下面我就介绍一下OkHttp的基本用法。
配置方法
(一)导入jar包
点击下面链接下载OkHttp最新jar包
https://repo1.maven.org/maven2/com/squareup/okhttp3/okhttp/3.9.1/okhttp-3.9.1.jar
(二)通过构建方式导入
MAVEN
1 2 3 4 5 6 |
<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.9.1</version> </dependency> |
GRADLE
1 2 |
compile 'com.squareup.okhttp3:okhttp:3.9.1' |
请求和响应
Request(请求)
每一个HTTP请求中都应该包含一个URL,一个GET或POST方法以及Header或其他参数,当然还可以含特定内容类型的数据流。
Responses(响应)
响应则包含一个回复代码(200代表成功,404代表未找到),Header和定制可选的body
基本使用
在日常开发中,最常用到的网络请求就是POST和GET两种请求方式。
Http GET
1 2 3 4 5 6 7 8 9 10 11 |
OkHttpClient client = new OkHttpClient(); String run(String url) throws IOException { Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } } |
上面这段代码中,Request是OkHttp中访问的请求,Builder是辅助类,,Response即OkHttp中的响应。
Response类:
1 2 3 4 |
public boolean isSuccessful() Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted. response.body()返回ResponseBody类 |
可以方便的获取String:
1 2 3 4 5 |
public final String string() throws IOException Returns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset, this will attempt to decode the response body as UTF-8. Throws: IOException |
获取流:
1 2 |
public final InputStream byteStream() |
Http POST
对于POST方式,我们最常提交的就是json数据和键值对了,我们来看看这两种情况怎么写。
POST提交Json数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); f (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } } |
使用Request的post方法来提交请求体RequestBody。
(这里附上OkHttp MediaType的使用:)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8"); 属性: text/html : HTML格式 text/plain :纯文本格式 text/xml : XML格式 image/gif :gif图片格式 image/jpeg :jpg图片格式 image/png:png图片格式 以application开头的媒体格式类型: application/xhtml+xml :XHTML格式 application/xml : XML数据格式 application/atom+xml :Atom XML聚合格式 application/json : JSON数据格式 application/pdf :pdf格式 application/msword : Word文档格式 application/octet-stream : 二进制流数据(如常见的文件下载) application/x-www-form-urlencoded : <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式) |
POST提交键值对
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody formBody = new FormEncodingBuilder() .add("platform", "android") .add("name", "bug") .add("subject", "XXXXXXXXXXXXXXX") .build(); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); } } |
Demo
下面是我写的一个小demo,就是通过提交用户名和密码到服务器来登录的一个小案例。使用了GET和POST两种方式。
布局文件
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 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.jyx.demo.myapplication.OkHttpActivity"> <EditText android:id="@+id/et_userName" android:layout_width="match_parent" android:layout_height="wrap_content" /> <EditText android:id="@+id/et_password" android:layout_width="match_parent" android:layout_height="50dp" /> <Button android:id="@+id/btn_send_get" android:layout_width="match_parent" android:layout_height="50dp" android:text="get登录"/> <Button android:id="@+id/btn_send_post" android:layout_width="match_parent" android:layout_height="50dp" android:text="post登录"/> </LinearLayout> |
Activity
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
package com.jyx.demo.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.squareup.okhttp.Callback; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import java.io.IOException; public class OkHttpActivity extends AppCompatActivity implements View.OnClickListener { private EditText mUserName; private EditText mPassword; private Button mLoginGet; private Button mLoginPost; private String loginName; private String loginPwd; private String url = "http://192.168.0.101:8080/ServerJing/LoginServlet"; private OkHttpClient client; public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ok_http); mUserName = (EditText) findViewById(R.id.et_userName); mPassword = (EditText) findViewById(R.id.et_password); mLoginGet = (Button) findViewById(R.id.btn_send_get); mLoginPost = (Button) findViewById(R.id.btn_send_post); client = new OkHttpClient(); mLoginGet.setOnClickListener(this); mLoginPost.setOnClickListener(this); } @Override public void onClick(View view) { loginName = mUserName.getText().toString(); loginPwd = mPassword.getText().toString(); switch (view.getId()){ case R.id.btn_send_post: loginByPost(loginName,loginPwd); break; case R.id.btn_send_get: try { loginByGet(loginName,loginPwd); } catch (IOException e) { e.printStackTrace(); } break; } } //异步get private void loginByGet(String name,String pwd) throws IOException { String finalUrl = url + "?" +"username=" + name +"&password=" + pwd; Request request = new Request.Builder().url(finalUrl).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Toast.makeText(OkHttpActivity.this,"failed",Toast.LENGTH_SHORT).show(); } @Override public void onResponse(Response response) throws IOException { byte[] bytes = response.body().bytes(); final String responseMsg = new String(bytes,"GBK"); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(),responseMsg,Toast.LENGTH_SHORT).show(); } }); } }); } //异步post private void loginByPost(String name,String pwd){ RequestBody formBody = new FormEncodingBuilder().add("username",name) .add("password",pwd).build(); Request request = new Request.Builder().url(url).post(formBody).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Toast.makeText(OkHttpActivity.this,"failed",Toast.LENGTH_SHORT).show(); } @Override public void onResponse(final Response response) throws IOException { byte[] bytes = response.body().bytes(); final String responseMsg = new String(bytes,"GBK"); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(),responseMsg,Toast.LENGTH_SHORT).show(); } }); } }); } } |
看完上面的代码,大家可能会有疑问,为什么和我开始列举的写法不一样呢,因为这个demo里面我用的是异步的方式。异步方式也很简单,就是将Request加入调度,然后等待任务执行完成,在Callback中可以直接得到结果,我写个小例子方便大家更直观的理解:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//创建okHttpClient对象 OkHttpClient mOkHttpClient = new OkHttpClient(); //创建一个Request final Request request = new Request.Builder() .url("https://github.com/woaixiaoronger") .build(); //new call Call call = mOkHttpClient.newCall(request); //请求加入调度 call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(final Response response) throws IOException { //String htmlStr = response.body().string(); } }); |
好,移动端代码写完了,们看下效果:
没错,就是这么一个简单的界面了。下面附上服务端代码,这里我就写了个简单的serverlet,然后部署到了tomcat上,如下:
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 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package com.jing.servlet; import java.io .IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.crypto.Data; import com.jing.dao.UsersDao; import com.jing.domain.Users; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoginServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet"); String username = request.getParameter("username"); String password = request.getParameter("password"); if("123".equals(username) && "123".equals(password)){ response.getOutputStream().write("登录成功".getBytes()); }else{ response.getOutputStream().write("登录信息有误".getBytes()); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("doPost"); doGet(request, response); } } |
移动端和服务端代码都有了,下面我们来测试下(由于我部署到tomcat上,我这里是把移动端安装到手机上,然后用手机连接笔记本的wifi进行测试的,IP地址ipconfig获取一下就好。):
图1.GET方法登录成功
图2.GET方法登录失败
图1.POST方法登录成功
好了,OkHttp的基本使用我就讲到这里了,因为更深层次的我还需要继续学习呀,下面附上官方的OkHttp官方Recipes链接:https://github.com/square/okhttp/wiki/Recipes,我们共同学习。最后欢迎指正,感谢阅读。
想获得去掉 5 元限制的证券账户吗?

如果您想去掉最低交易佣金 5 元限制,使用微信扫描左边小程序二维码,访问微信小程序「优财助手」,点击底部菜单「福利」,阅读文章「通过优财开证券账户无最低交易佣金 5 元限制」,按照文章步骤操作即可获得免 5 元证券账户,股票基金交易手续费率万 2.5。
请注意,一定要按照文章描述严格操作,如错误开户是无法获得免 5 元证券账户的。