Java android multipart / form-data发送请求

时间:2017-12-12 06:51:25

标签: android multipartform-data

我想发送multipart/form-data。我想在一个请求中发送一张照片和json。我这样做了:

  JSONObject jsonObject = new JSONObject();
    SharedPreferences sp ;
    sp = getSharedPreferences("pfref", Activity.MODE_PRIVATE);
    String pass = sp.getString("pass", "");
    String firm = sp.getString("firm", "");
    String login = sp.getString("login", "");

    try {
        jsonObject.put("company", firm);
        jsonObject.put("user", login);
        jsonObject.put("secure_password", HashUtil.md5(pass));
        jsonObject.put("secure_device_id", HashUtil.md5(DeviceUtil.getDeviceId(PhotoActivity.this)));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    ImageLoader imageLoader = ImageLoader.getInstance();

    FileEntity fileEntity = null;
    try {
        fileEntity = new FileEntity(file, "image/jpeg");
    } catch (Exception e) {
        e.printStackTrace();
    }

    RequestParams params = new RequestParams();
    BasicHeader[] headers = new BasicHeader[]{new BasicHeader("Authorization", "SCToken " + token)};
    params.put("photos", fileEntity);
    params.put("metadata",jsonObject);

    client.post(PhotoActivity.this, RestClient.getAbsoluteUrl("photos/note"), headers, params, "multipart/form-data", new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            Log.d("sokces", "uploadFile response: " + statusCode);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            Log.d("sokces fail", "uploadFile ERROR! " + statusCode);
        }
    });

但它不起作用。当我将内容类型更改为application/json时,我有415 status,但当我有multipart/form-data时,我有400 status。这是失败状态。

1 个答案:

答案 0 :(得分:0)

你的REST服务应该喜欢这个

@POST
    @Path("/pic")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
            @FormDataParam("file") InputStream uploadedInputStream,
            @FormDataParam("file") FormDataContentDisposition fileDetail,
            @FormParam("json") String json)
{
         ...............
            JSONObject jsonObject=new JSONObject(json);

}

使用Retrofit APi

 @Multipart
    @POST("TestService/upload/pic")
    Call<ResponseBody> Upload_Docs(@Part MultipartBody.Part body,@Field("json") String json);

在您的活动中

Retrofit retrofit = Retrofit_Api.getClient();
Service_Interface service_interface = retrofit.create(Service_Interface.class);

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                RequestBody body = RequestBody.create(okhttp3.MediaType.parse("multipart/form-data"), file1);
                MultipartBody.Part body11 = MultipartBody.Part.createFormData("file", file1.getName(), body);

String json="{ "name":"test"}";
Call<ResponseBody> call = service_interface.Upload_Docs(body11,json);

                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            Utils.Toast_L(getContext(), response.body().string());
                            // if(fileToUpload.delete());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Utils.Toast_L(getContext(), t.toString());
                    }
                });

 }
        });

改造APi类似乎

public class Retrofit_Api {

    public static final String BASE_URL = "http://192.168.2.102:2323/"; // your base URL
    public static Retrofit retrofit = null;


    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit =new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

Retrofit将您的HTTP API转变为Java接口。

Service_Interface类看起来像

public interface Service_Interface {

            @Multipart
            @POST("TestService/upload/pic")
            Call<ResponseBody> Upload_Docs(@Part MultipartBody.Part body,@Field("json") String json);


    }