OkHttp的基本使用(附服务端代码)

引言

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

  com.squareup.okhttp3
  okhttp
  3.9.1

 

GRADLE

compile 'com.squareup.okhttp3:okhttp:3.9.1'
 

请求和响应

Request(请求)

每一个HTTP请求中都应该包含一个URL,一个GET或POST方法以及Header或其他参数,当然还可以含特定内容类型的数据流。

Responses(响应)

响应则包含一个回复代码(200代表成功,404代表未找到),Header和定制可选的body

基本使用

在日常开发中,最常用到的网络请求就是POST和GET两种请求方式。

Http GET

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类:

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:

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
 

获取流:

public final InputStream byteStream()
 

Http POST

对于POST方式,我们最常提交的就是json数据和键值对了,我们来看看这两种情况怎么写。

POST提交Json数据

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的使用:)

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 : 
中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)

POST提交键值对

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两种方式。

布局文件


 
    
    
 
    

Activity

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中可以直接得到结果,我写个小例子方便大家更直观的理解:

//创建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上,如下:

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 ,我们共同学习。最后欢迎指正,感谢阅读。

责编内容来自:技术学习小组 (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 移动开发 » OkHttp的基本使用(附服务端代码)

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录