如何将多部分表单数据从android发布到web api?

问题描述 投票:0回答:3

我想在图片中准确发布。从邮递员工作的好。我不知道如何在Android中做到这一点。 TIA

在postman:https://i.stack.imgur.com/2lc3m.png中查看我的请求图片

android asp.net-web-api multipartform-data form-data
3个回答
0
投票

关于stackoverflow上有很多关于multipart的帖子,试试这个

public static String uploadMultipartFile(String root, String token,
                         String username, String sourceFileUri,
                         String fileStyle)
{
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    String pathToOurFile = sourceFileUri;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    StringBuffer response = new StringBuffer();
    try
    {
        FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
        URL url = new URL(root);
        connection = (HttpURLConnection) url.openConnection();

        if (token != null)
        {
            connection.setRequestProperty("Authorization", "Basic " + token);
        }
        if (username != null)
        {
            connection.setRequestProperty("Username", username);
        }
        if (fileStyle != null)
        {
            connection.setRequestProperty("file-type", fileStyle);
        }

        String fileExtension = FilenameUtils.getExtension(sourceFileUri);
        String mime = Utils.getFileMIME(fileExtension);

        Log.d("uploadMultipartFile","fileExtension:"+fileExtension+",mime:"+mime);

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("User-Agent", "CodeJava Agent");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                + pathToOurFile + "\"" + lineEnd);
        outputStream.writeBytes("Content-Type: "+ mime + lineEnd);

        outputStream.writeBytes(lineEnd);

        byte[]bytes = IOUtils.toByteArray(fileInputStream);
        outputStream.write(bytes);

        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        int serverResponseCode = connection.getResponseCode();
        String serverResponseMessage = connection.getResponseMessage();
        Log.i(HttpUtil.class.getSimpleName(), String.valueOf(serverResponseCode));
        Log.i(HttpUtil.class.getSimpleName(), serverResponseMessage);

        fileInputStream.close();
        outputStream.flush();
        outputStream.close();

        BufferedReader br=null;
        if(connection.getResponseCode()>=200 && connection.getResponseCode()<300)
        {
            br = new BufferedReader(new InputStreamReader((connection.getInputStream())));

        }
        else if(connection.getResponseCode()>=400)
        {
            br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));
        }
        String inputLine;
        while ((inputLine = br.readLine()) != null) {
            response.append(inputLine);
        }
        System.out.println("result from server:"+response.toString());
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
    return response.toString();
}

0
投票

您需要将您的jpg文件转换为位图对象,然后您需要将其压缩为字节数组以发送多部分请求。

   public class FileUpload extends Activity {
        Bitmap bm;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            try {
                // bm = BitmapFactory.decodeResource(getResources(),
                // R.drawable.forest);
                bm = BitmapFactory.decodeFile("/sdcard/DCIM/yourImage.jpg");
                executeMultipartPost();
            } catch (Exception e) {
                Log.e(e.getClass().getName(), e.getMessage());
            }
        }

        public void executeMultipartPost() throws Exception {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bm.compress(CompressFormat.JPEG, 75, bos);
                byte[] data = bos.toByteArray();
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(
                        "http://10.0.2.2/cfc/iphoneWebservice.cfc?returnformat=json&amp;method=testUpload");
                ByteArrayBody bab = new ByteArrayBody(data, "yourImage.jpg");
                // File file= new File("/mnt/sdcard/yourImage.jpg");
                // FileBody bin = new FileBody(file);
                MultipartEntity reqEntity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("uploaded", bab);
                reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
                postRequest.setEntity(reqEntity);
                HttpResponse response = httpClient.execute(postRequest);
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent(), "UTF-8"));
                String sResponse;
                StringBuilder s = new StringBuilder();

                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }
                System.out.println("Response: " + s);
            } catch (Exception e) {
                // handle exception here
                Log.e(e.getClass().getName(), e.getMessage());
            }
        }
    }

0
投票

将其添加到您的gradle构建中

compile('org.apache.httpcomponents:httpmime:4.3.6') {
    exclude module: 'httpclient'
}

在webservice类中编写代码,如下所述

 public MyPojo post(String name, String gender, String celbID) {

 MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();

        multipartEntity.addPart("Name", new StringBody(name, ContentType.TEXT_PLAIN));
        multipartEntity.addPart("gender", new StringBody(gender, ContentType.TEXT_PLAIN));
        multipartEntity.addPart("Celb_id", new StringBody(celbID, ContentType.TEXT_PLAIN));

        httppost.setEntity(multipartEntity.build());
        HttpResponse httpResponse = httpclient.execute(httppost);
        HttpEntity httpEntity = httpResponse.getEntity();
        aJsonResponse = EntityUtils.toString(httpEntity);

一旦你对此有疑问,请打我...

© www.soinside.com 2019 - 2024. All rights reserved.