今天,简单讲讲Android 使用OK HTTP上传图片。
不废话了,直接上代码:
/**
* 上传图片
* @param url
* @param imagePath 图片路径
* @return 新图片的路径
* @throws IOException
* @throws JSONException
*/
public static String uploadImage(String url, String imagePath) throws IOException, JSONException {
OkHttpClient okHttpClient = new OkHttpClient();
Log.d("imagePath", imagePath);
File file = new File(imagePath);
RequestBody image = RequestBody.create(MediaType.parse("image/png"), file);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", imagePath, image)
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject.optString("image");
}
直接在okHttp时调用函数就可以了。
Android okHttp上传图片就讲完了。
就这么简单。