视频讲解 https://www.bilibili.com/video/BV1aA411e7jV
后台请求文档 https://github.com/TrillGates/SOBAndroidMiniWeb
学习使用,实际工作要封装起来,线程管理起来
目录
基本get请求
public void getRequest(View view) {
//客户端
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
//创建请求内容
final Request request = new Request.Builder()
.get()
.url("http://10.0.2.2:9102/get/text")
.build();
//用Client去创建请求任务
Call call = client.newCall(request);
//异步请求
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.d(TAG, "onFailure: " + e.toString());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String string = response.body().string();
Log.d(TAG, "onResponse: " + string);
int code = response.code();
Log.d(TAG, "onResponse: " + code);
}
});
}
带参数的get请求
public void getParameter(View view) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
Map<String, String> map = new HashMap<>();
map.put("keyword", "key");
map.put("page", "12");
map.put("order", "0");
StringBuilder sb = new StringBuilder();
sb.append("?");
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
sb.append(next.getKey());
sb.append("=");
sb.append(next.getValue());
if (iterator.hasNext()) {
sb.append("&");
}
}
String s = sb.toString();
Log.e(TAG, "----" + s);
Request request = new Request.Builder()
.url(base_url1 + "/get/param" + s)
.get()
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.e(TAG, "onFailure: " + e.toString());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
Log.e(TAG, "onResponse: " + response.code());
Log.e(TAG, "onResponse: " + response.body().string());
}
});
}
post请求方法带参数
public void postParameter(View view) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000,TimeUnit.MILLISECONDS)
.build();
FormBody.Builder builder = new FormBody.Builder();
RequestBody requestBody = builder
.add("userName","123")
.add("password","123456")
.build();
Request request = new Request.Builder()
.url(base_url1 + "/login")
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.e(TAG, "onFailure: " + e.toString());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
Log.e(TAG, "onResponse: " + response.code());
Log.e(TAG, "onResponse: " + response.body().string());
}
});
}
提交评论
public void postComment(View view) {
//客户端
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.build();
//提交内容
CommandItem commandItem = new CommandItem("123456", "hello!");
Gson gson = new Gson();
String jsonstr = gson.toJson(commandItem);
MediaType mediaType = MediaType.parse("application/json");
RequestBody requestBody = RequestBody.create(jsonstr, mediaType);
final Request request = new Request.Builder()
.url(base_url + "/post/comment")
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.e(TAG, "onFailure: " + e.toString());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
int code = response.code();
Log.e(TAG, "onResponse: " + code);
if (code == HTTP_OK) {
ResponseBody body = response.body();
Log.e(TAG, "onResponse: " + body.string());
}
}
});
}
请求网络图片
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(8, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.get()
.url(Constants.imageUrl)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
InputStream inputStream = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Message message = mHandler.obtainMessage();
message.obj = bitmap;
mHandler.sendMessage(message);
}
});
private final Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message message) {
if (mProgressBarMore != null) {
mProgressBarMore.setVisibility(View.GONE);
}
Bitmap bitmap = (Bitmap) message.obj;
mIvMore.setImageBitmap(bitmap);
return false;
}
});
上传单文件
public void postFile(View view) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000,TimeUnit.MILLISECONDS)
.build();
File file = new File("/storage/self/primary/Download/u=2604811881,2055398559&fm=173&app=49&f=JPEG.jpg");
MediaType mediaType = MediaType.parse("image/png");
RequestBody filebody = RequestBody.create(file,mediaType);
RequestBody requestBody = new MultipartBody.Builder()
.addFormDataPart("file",file.getName(),filebody)
.build();
Request request = new Request.Builder()
.url(base_url + "/file/upload")
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.e(TAG, "onFailure: "+e.toString() );
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
int code = response.code();
Log.e(TAG, "onResponse: "+code);
if (code == HTTP_OK){
Log.e(TAG, "onResponse: "+response.body().string() );
}
}
});
}
下载文件
public void DownloadFiles(View view) {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10000,TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url(base_url1+"/download/15")
.get()
.build();
final Call call = client.newCall(request);
new Thread(new Runnable() {
@Override
public void run() {
InputStream inputStream = null;
FileOutputStream fos = null;
try {
Response execute = call.execute();
Headers headers = execute.headers();
for (int i = 0; i < headers.size(); i++) {
Log.e(TAG, "run: "+headers.name(i) + " "+headers.value(i));
}
String contentType = headers.get("Content-disposition");
String fileName = contentType.replace("attachment; filename=", "");
File outFile = new File(OkhttpActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES)+ File.separator+fileName);
if (outFile.getParentFile().exists()) {
outFile.mkdirs();
}
if(!outFile.exists()){
outFile.createNewFile();
}
fos = new FileOutputStream(outFile);
if (execute.body()!=null) {
inputStream = execute.body().byteStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer,0,buffer.length))!=-1){
fos.write(buffer,0,len);
}
fos.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (inputStream!=null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos!=null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
}
okhttp封装起来
public abstract class ResultCallback {
public abstract void onError(Request request, Exception e);
public abstract void onResponse(String str) throws IOException;
}
public class OkhttpUtil {
private static volatile OkhttpUtil mInstance;
private OkHttpClient mOkHttpClient;
private Handler mHandler;
public static OkhttpUtil getInstance() {
if (mInstance == null) {
synchronized (OkhttpUtil.class) {
if (mInstance == null) {
mInstance = new OkhttpUtil();
}
}
}
return mInstance;
}
private OkhttpUtil() {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.readTimeout(1000, TimeUnit.MILLISECONDS)
.connectTimeout(1000,TimeUnit.MILLISECONDS);
mOkHttpClient = builder.build();
mHandler = new Handler();
}
public void getAsynHttp(String url, ResultCallback callback) {
Request request = new Request.Builder()
.url(url)
.build();
Call call = mOkHttpClient.newCall(request);
dealResult(call, callback);
}
private void dealResult(Call call, final ResultCallback callback) {
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
sendFailedCallback(call.request(), e, callback);
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
sendSuccessCallback(response.body().string(), callback);
}
});
}
private void sendSuccessCallback(final String string, final ResultCallback callback) throws IOException {
mHandler.post(new Runnable() {
@Override
public void run() {
try {
callback.onResponse(string);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void sendFailedCallback(final Request request, final IOException e, final ResultCallback callback) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (callback != null) {
callback.onError(request, e);
}
}
});
}
}
封装类的使用
OkhttpUtil okhttpUtil = OkhttpUtil.getInstance(BaseApplication.getContext());
okhttpUtil.getAsynHttp(url, new ResultCallback() {
@Override
public void onError(Request request, Exception e) {
Log.e(TAG, "onFailure: " + e.toString());
}
@Override
public void onResponse(String str) throws IOException {
}
});