Android OkHttp基本用法
Posted 瞌睡先生想睡觉
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android OkHttp基本用法相关的知识,希望对你有一定的参考价值。
引用:
compile 'com.squareup.okhttp3:okhttp:3.8.1'
compile 'com.squareup.okio:okio:1.13.0'
android Activity:
package com.example.okhttpdemo;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OkHttpClient client = new OkHttpClient();
/**
* get请求
* @param view
*/
public void httpGet(View view)
new Thread()
@Override
public void run()
String result = "";
Request request = new Request.Builder()
.url("http://192.168.3.177:8080/Test/Test?action=getMessage")
.build();
try
Response response = client.newCall(request).execute();
result = response.body().string();
catch (IOException e)
e.printStackTrace();
d(result);
.start();
/**
* post请求
* @param view
*/
public void httpPost(View view)
new Thread()
@Override
public void run()
String result = "";
RequestBody body = new FormBody.Builder()
.add("action", "getMessage")
.build();
Request request = new Request.Builder()
.url("http://192.168.3.177:8080/Test/Test")
.post(body)
.build();
try
Response response = client.newCall(request).execute();
result = response.body().string();
catch (IOException e)
e.printStackTrace();
d(e.toString());
d(result);
.start();
/**
* 下载文件
* @param view
*/
public void downloadFile(View view)
new Thread()
@Override
public void run()
String url = "https://www.baidu.com/img/bd_logo1.png";
Request request = new Request.Builder().url(url).build();
try
Response response = client.newCall(request).execute();
InputStream inputStream = response.body().byteStream();
String path = Environment.getExternalStorageDirectory().getPath() + "/baidu.png";
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
byte[] bs = new byte[1024];
int l = 0;
while ((l = inputStream.read(bs)) != -1)
fileOutputStream.write(bs, 0, l);
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
catch (IOException e)
e.printStackTrace();
.start();
/**
* 上传文件
* @param view
*/
public void uploadFile(View view)
new Thread()
@Override
public void run()
String url = "http://192.168.3.177:8080/Test/Test?action=uploadFile&fileName=";
String path = Environment.getExternalStorageDirectory().getPath() + "/baidu.png";
final File file = new File(path);
if(!file.exists())
return;
url+=file.getName();
RequestBody requestBody =RequestBody.create(MediaType.parse("application/octet-stream"),file);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try
Response result = client.newCall(request).execute();
int resultCode = result.code();
d(String.valueOf(resultCode));
catch (IOException e)
e.printStackTrace();
.start();
public void d(String string)
Log.d("Ex", string);
上传的文件为了省事直接用的就是下载文件时所下载的文件
Java服务器Servlet接口代码:
package code.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet
/**
*
*/
private static final long serialVersionUID = 4593404916826953969L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
doPost(req, resp);
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html; charset=UTF-8");
PrintWriter out = resp.getWriter();
String action = req.getParameter("action");
if (action == null)
action = "";
/**
* 获取信息
*/
if (action.equalsIgnoreCase("getMessage"))
out.println("举头忽见衡阳雁。千声万字情何限。" + "叵而薄情夫。一行书也无。 " + "泣归香阁恨。和泪掩红粉。" + "待雁却回时。也无书寄伊。");
/**
* 上传数据
*/
if (action.equalsIgnoreCase("uploadFile"))
String fileName=req.getParameter("fileName");
try
InputStream inputStream = req.getInputStream();
File file = new File("D:\\\\"+fileName);
if (!file.exists())
file.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] bs = new byte[1024];
int l = 0;
while ((l = inputStream.read(bs)) != -1)
fileOutputStream.write(bs, 0, l);
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
catch (IOException e)
e.printStackTrace();
out.flush();
out.close();
之前写Android进行网络请求一开始学习的时候用的是Android自带的api,之后来到我的第一家公司也比较自由,并没有限制网络访问所用的框架什么的,所以学习了NoHttp的使用,现在想的是OkHttp毕竟使用的公司很多,所以就花点时间简单的研究下,记录下,以后如果用到不会太麻烦的从头开始,也没有太深入
关于Android网络请求和文件操作的权限自行添加
以上是关于Android OkHttp基本用法的主要内容,如果未能解决你的问题,请参考以下文章