天天看點

Android okHttp上傳圖檔

今天,簡單講講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上傳圖檔就講完了。

就這麼簡單。