一.post请求上传 (1)导入okhttp3
implementation 'com.squareup.okhttp3:okhttp:3.10.0'(2)post上传方法使用
注:使用的时候记得要开线程,不然会报错
new Thread(new Runnable() {
@Override
public void run() {
try {
uploadImage(url, deviceID, Bitmap2StrByBase64(finalBitmap));
} catch (IOException e) {
e.printStackTrace();
Log.i("1111111", "IOException e :" + e.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.i("1111111", "JSONException e :" + e.toString());
}
}
}).start();
/**
* post上传
* 以上传图片为例
* @param url 服务器地址,必须字段
* @param deviceID 接口所需的键值对数据,非必需字段
* @param s 接口所需的键值对数据,非必需字段
* @throws IOException
* @throws JSONException
*/
public void uploadImage(String url, String deviceID, String s) throws IOException, JSONException {
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("token", deviceID) //以下为接口对应的键值对,根据接口进行变动
.addFormDataPart("upfile", s)
.addFormDataPart("upload_type", "base64")
.addFormDataPart("water", "no")
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) { //响应成功
//解析服务器返回的数据,因只需要一个字段的数据,此处使用的是JSONObject解析,没有使用Gson
//注:response.body().string() 只能调用一次,多次调用会报错,可调用一次赋值后,多次使用赋值参数
String data = response.body().string();
Log.i("1111111", "返回的数据:" + data);
JSONObject object = new JSONObject(data);
String state = object.getString("state");
if (state.equals("SUCCESS")) {
Log.i("1111111", "上传成功");
} else {
Log.i("1111111", "上传失败");
}
}
}
(2)Get请求
/**
* 下载图片
*
* @param url 服务器地址
* @param imagePath 图片路径
* @return byte[]
* @throws IOException
*/
public static byte[] downloadImage(String url, String imagePath) throws IOException {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url + "/show?fileName=" + imagePath)
.build();
Response response = okHttpClient.newCall(request).execute();
byte[] bytes = response.body().bytes();
return bytes;
}
至此。