Android 网络编程之最新OKHTTP:3.9.0

 

本节前言

原本是想围绕着HttpClient讲解的,后来发先Android4.4以后okhttp代替了hc,因此将再也不讲解hccss

okhttp的简单使用,主要包含:java

  • 通常的get请求
  • 通常的post请求
  • 基于Http的文件上传
  • 文件下载
  • 加载图片
  • 支持请求回调,直接返回对象、对象集合
  • 支持session的保持

使用okhttp

使用okhttp前首先要添加依赖json

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

通常的get请求

对了网络加载库,那么最多见的确定就是http get请求了,好比获取一个网页的内容数组

OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); String string = response.body().string(); System.out.println(string); } 

运行结果tomcat

 
  • 以上就是发送一个get请求的步骤,首先构造一个Request对象,参数最起码有个url,固然你能够经过Request.Builder设置更多的参数好比:header、method等。服务器

  • 而后经过request的对象去构造获得一个Call对象,相似于将你的请求封装成了任务,既然是任务,就会有execute()和cancel()等方法。网络

  • 最后,咱们但愿以异步的方式去执行请求,因此咱们调用的是call.enqueue,将call加入调度队列,而后等待任务执行完成,咱们在Callback中便可获得结果。session

  • onResponse回调的参数是response,通常状况下,好比咱们但愿得到返回的字符串,能够经过response.body().string()获取;若是但愿得到返回的二进制字节数组,则调用response.body().bytes();若是你想拿到返回的inputStream,则调用response.body().byteStream()app

通常的post请求

1) POST提交键值对

不少时候咱们会须要经过POST方式把键值对数据传送到服务器。 OkHttp提供了很方便的方式来作这件事情。好比提交用户名和密码用来登陆异步

post提交键值对其实和get方法之多了一个RequestBody,用来添加键值对

get提交链接以下

http://192.168.56.1:8080/LoginServlet?username=abc&password=123 

post提交链接以下

OkHttpClient client = new OkHttpClient(); RequestBody requestBody=new FormBody.Builder() .add("username","abc") .add("password","123") .build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); Response response = client.newCall(request).execute(); String string = response.body().string(); System.out.println(string); } 

是否是比hc简单多了,这里须要注意到一点是最新版的okhttp,原来的FormEncodingBuilder被FormBody代替了

POST提交Json数据

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); return response.body().string(); 

下载文件

new Thread(){public void run(){ OkHttpClient client = new OkHttpClient(); Request request=new Request.Builder().url("http://192.168.56.1:8080/tomcat.png").build(); try { Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { System.out.println("下载失败"); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream in=response.body().byteStream(); FileOutputStream fos=new FileOutputStream(new File(getFilesDir(),"11.png")); int len=0; byte []bytes=new byte[1024]; while ((len=in.read(bytes))!=-1){ fos.write(bytes,0,len); } fos.flush(); } }); } catch (Exception e) { e.printStackTrace(); } }}.start(); 

其实仔细看仍是和上面的get请求差很少,无非就是get下载了,这里就只是改变了

Call call = client.newCall(request);
                call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { //链接失败 } @Override public void onResponse(Call call, Response response) throws IOException { //链接成功 } 

上传文件

public static void doFile(String url, String pathName, String fileName, Callback callback) { //判断文件类型 MediaType MEDIA_TYPE = MediaType.parse(judgeType(pathName)); //建立文件参数 MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart(MEDIA_TYPE.type(), fileName, RequestBody.create(MEDIA_TYPE, new File(pathName))); //发出请求参数 Request request = new Request.Builder() .header("Authorization", "Client-ID " + "9199fdef135c122") .url(url) .post(builder.build()) .build(); Call call = getInstance().newCall(request); call.enqueue(callback); } /** * 根据文件路径判断MediaType * * @param path * @return */ private static String judgeType(String path) { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentTypeFor = fileNameMap.getContentTypeFor(path); if (contentTypeFor == null) { contentTypeFor = "application/octet-stream"; } return contentTypeFor; } 
相关文章
相关标签/搜索