Upload multipart image data in JSON with Retrofit?

后端 未结 3 1732
清酒与你
清酒与你 2021-01-04 20:06

I would like to do a PUT request with this JSON body (containing a picture) and with Retrofit. I\'m using it under Android:

{
    \"Request\": {
        \"da         


        
3条回答
  •  滥情空心
    2021-01-04 20:43

    You need to put image data in byte by using multipart form data.

    try {
        HttpPost httppost = new HttpPost("some url");
        MultipartEntity multipartEntity = 
            new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
        multipartEntity.addPart("Image", new FileBody(image));
        httppost.setEntity(multipartEntity);
        mHttpClient.execute(httppost, new YOURHANDLER());
    } catch (Exception e) {
        Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e);
    }
    

    To send post request using parameters

    HttpPost httpPost = new HttpPost(url);
    List nameValuePairs = new ArrayList();
    
    if (values != null) {
        for (Map.Entry entry : values.entrySet()) {
            nameValuePairs.add(
                new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
    }
    

提交回复
热议问题