okhttp3上传图片
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                okhttp3上传图片
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                1.okhttp上傳文件步驟
public class ImageUpload{//1.創(chuàng)建對應的MediaTypeprivate static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");private final OkHttpClient client = new OkHttpClient();public void uploadImage(String userName,File file) throws NetworkException{//2.創(chuàng)建RequestBodyRequestBody fileBody = RequestBody.create(MEDIA_TYPE_PNG, file);//3.構建MultipartBodyRequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", "testImage.png", fileBody).addFormDataPart("userName", userName).build();//4.構建請求Request request = new Request.Builder().url("http://xxxxx").post(requestBody).build();//5.發(fā)送請求Response response = client.newCall(request).execute();} }2.常用MediaType類型
json : application/json xml : application/xml png : image/png jpg : image/jpeg gif : imge/gif3.addFormDataPart是對addPart封裝:
addPart( Headers.of(“Content-Disposition”, “form-data; name=\”file\”;filename=\“testImage.png\""), RequestBody.create(MEDIA_TYPE_PNG, fileBody))addPart( Headers.of(“Content-Disposition”, “form-data; name=\”userName\”“), RequestBody.create(null, userName))總結
以上是生活随笔為你收集整理的okhttp3上传图片的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 拓扑学 -- from BBS 水木清华
 - 下一篇: nLite - 整合驱动程序 - PNP