okhttp post 서버 파일 업로드 요청

4226 단어
 
public class HeadMobile {
    private HeadView headView;
    
    public void head(String mobile,File file){
        OkHttpClient client=new OkHttpClient();
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
            // MediaType.parse()  。
            RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
            String filename = file.getName();
            //  ,  key ,  , RequestBody
            requestBody.addFormDataPart("file", file.getName(), body);
            requestBody.addFormDataPart("mobile",mobile);

        Request request = new Request.Builder().post(requestBody.build()).url(Api.LOADURL).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
              headView.onfailure(call,e);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String rs = response.body().string();

                try {
                   JSONObject js=new JSONObject(rs);
                    String code = js.getString("code");
                    String msg = js.getString("msg");
                    if(code.equals("0")){
                        headView.hedaSuccees(code,msg);
                    }else{
                        headView.hedaFail(code,msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public void setHeadView(HeadView headView) {
        this.headView = headView;
    }
    public interface HeadView{
        void hedaSuccees(String code,String msg);
        void hedaFail(String code,String msg);
        void onfailure(Call call, IOException e);
    }
}

좋은 웹페이지 즐겨찾기