1使用okhttp3发送http请求,添加依赖
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
2.创建回调接口
ackage com.cmeim.pcp.pda.callback;
import org.json.JSONException;
/**
* 自定义回调
*/
public interface ResponseCallBack {
void success(String json) throws JSONException;
void error(String json);
}
3.创建一个工具类
package com.cmeim.pcp.pda.utils;
import android.os.Handler;
import android.util.Log;
import com.cmeim.pcp.pda.callback.ResponseCallBack;
import com.cmeim.pcp.pda.dialog.CustomProgressDialog;
import com.cmeim.pcp.pda.vo.HttpUrlVo;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Description : OkHttp网络连接封装工具类
* Author :
* Date : 2020年7月1日15:51:20
*/
public class OkHttpUtils {
private static final String TAG = "OkHttpUtils";
//handler主要用于异步请求数据之后更新UI
private static Handler handler = new Handler();
public static void getAsync(String url,ResponseCallBack responseCallBack) {
OkHttpClient client = new OkHttpClient();
Log.i(TAG,"请求地址===》"+url);
Request request = new Request
.Builder()
.addHeader("Cookie","token="+ HttpUrlVo.TOKEN)
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.e(TAG,"响应失败===》"+e.getMessage());
handler.post(()->{
responseCallBack.error(e.getMessage());
});
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String respBody=response.body().string();
Log.i(TAG,"响应成功===》"+respBody);
handler.post(()->{
try {
responseCallBack.success(respBody);
} catch (JSONException e) {
e.printStackTrace();
ActivityUtils.showLogToast("程序出现异常:"+e.getMessage());
}
});
}
});
}
/**
* 表单提交数据
* @param url 请求地址
* @param formData 表单回调
* @param responseCallBack 响应回调
*/
public static void postAsyncFormData(String url, Map<String,String> formData, ResponseCallBack responseCallBack) {
OkHttpClient client = new OkHttpClient().newBuilder().
callTimeout(30, TimeUnit.SECONDS)
.build();
FormBody.Builder builder = new FormBody.Builder();
StringBuffer showData=new StringBuffer();
for (String key:formData.keySet()){
builder.add(key,formData.get(key));
showData.append(" "+key+":"+formData.get(key));
}
FormBody formBody = builder
.build();
Request request = new Request
.Builder()
.addHeader("Cookie","token="+ HttpUrlVo.TOKEN)
.url(url)
.post(formBody)
.build();
Log.i(TAG,"开始发送请求:请求地址【"+url+"】,请求参数==>"+showData);
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.e(TAG,"响应失败===》"+e.getMessage());
handler.post(()->{
responseCallBack.error(e.getMessage());
});
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String respBody=response.body().string();
Log.i(TAG,"响应成功===》"+respBody);
handler.post(()->{
try {
responseCallBack.success(respBody);
} catch (JSONException e) {
ActivityUtils.showLogToast("程序出现异常:"+e.getMessage());
}
});
}
});
}
/**
* json提交数据
* @param url 请求地址
* @param json json数据
* @param responseCallBack 响应回调
*/
public static void postAsyncJson(String url, String json, ResponseCallBack responseCallBack) {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);
Request request = new Request.
Builder()
.url(url)
.addHeader("Cookie","token="+ HttpUrlVo.TOKEN)
.post(requestBody)
.build();
Log.i(TAG,"开始发送请求:请求地址【"+url+"】,请求参数==>"+json);
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.e(TAG,"响应失败===》"+e.getMessage());
handler.post(()->{
responseCallBack.error(e.getMessage());
});
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String respBody=response.body().string();
Log.i(TAG,"响应成功===》"+respBody);
handler.post(()->{
try {
responseCallBack.success(respBody);
} catch (JSONException e) {
ActivityUtils.showLogToast("程序出现异常:"+e.getMessage());
}
});
}
});
}
/**
* json提交数据
* @param url 请求地址
* @param json json数据
* @param responseCallBack 响应回调
*/
public static void putAsyncJson(String url, String json, ResponseCallBack responseCallBack) {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);
Request request = new Request.
Builder()
.url(url)
.addHeader("Cookie","token="+ HttpUrlVo.TOKEN)
.put(requestBody)
.build();
Log.i(TAG,"开始发送请求:请求地址【"+url+"】,请求参数==>"+json);
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.e(TAG,"响应失败===》"+e.getMessage());
handler.post(()->{
responseCallBack.error(e.getMessage());
});
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String respBody=response.body().string();
Log.i(TAG,"响应成功===》"+respBody);
handler.post(()->{
try {
responseCallBack.success(respBody);
} catch (JSONException e) {
ActivityUtils.showLogToast("程序出现异常:"+e.getMessage());
}
});
}
});
}
/**
* json提交数据
* @param url 请求地址
* @param formData 表单数据
* @param responseCallBack 响应回调
*/
public static void putAsyncForm(String url, Map<String,String> formData, ResponseCallBack responseCallBack) {
OkHttpClient client = new OkHttpClient().newBuilder().
callTimeout(30, TimeUnit.SECONDS)
.build();
FormBody.Builder builder = new FormBody.Builder();
StringBuffer showData=new StringBuffer();
for (String key:formData.keySet()){
builder.add(key,formData.get(key));
showData.append(" "+key+":"+formData.get(key));
}
FormBody formBody = builder
.build();
Request request = new Request
.Builder()
.addHeader("Cookie","token="+ HttpUrlVo.TOKEN)
.url(url)
.put(formBody)
.build();
Log.i(TAG,"开始发送请求:请求地址【"+url+"】,请求参数==>"+showData);
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
Log.e(TAG,"响应失败===》"+e.getMessage());
handler.post(()->{
responseCallBack.error(e.getMessage());
});
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String respBody=response.body().string();
Log.i(TAG,"响应成功===》"+respBody);
handler.post(()->{
try {
responseCallBack.success(respBody);
} catch (JSONException e) {
ActivityUtils.showLogToast("程序出现异常:"+e.getMessage());
}
});
}
});
}
}
4.测试post表单提交调用
Map<String, String> map = new HashMap<>();
map.put("pickId", "pickId");
map.put("qty", "qty");
map.put("stockId", "stockId");
OkHttpUtils.postAsyncFormData("http://localhost:8080/mm/pick/receive/pkgBar", map, new ResponseCallBack() {
@Override
public void success(String json) throws JSONException {
Log.e("响应数据",json)
}
@Override
public void error(String json) {
}
});