Android多部分请求web api没有获得与请求相关联的文本

时间:2015-12-10 07:44:31

标签: java android api http

您好我正在使用android。我想将多部分数据发送到asp.net web api。我有一个json数据和多个images.I使用以下方法将数据发布到api

 public int uploadFile(Context context,ArrayList<String> sourceFileUri,String json,String url1) {

        //    Toast.makeText(this,"uploading...", Toast.LENGTH_SHORT).show();


        StrictMode.ThreadPolicy policy = new
                StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        Log.i("uploadimage", "" + sourceFileUri.get(0));

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(android.os.Environment.getExternalStorageDirectory() + "/TrackonPro", sourceFileUri.get(0));

        if (!sourceFile.isFile()) {

            Log.i("uploadFile", "Source File not exist :" + sourceFileUri);
            return 0;
        }
        else
        {
            //   Toast.makeText(this,"found Path :  "+imagePath , Toast.LENGTH_LONG).show();

            try {

                //      Toast.makeText(this,"try....", Toast.LENGTH_LONG).show();

                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL(url1);

                // Open a HTTP  connection to  the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

                //       Toast.makeText(this,"url  :  "+ url, Toast.LENGTH_LONG).show();

                dos = new DataOutputStream(conn.getOutputStream());


                dos.writeBytes(twoHyphens + boundary + lineEnd);


                // JSON STRING
                dos.writeBytes("Content-Disposition: form-data; name=\"sanu\"");

                dos.writeBytes(lineEnd);

                dos.writeBytes(json);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);


                Log.i("immmm11",""+dos);


                // IMAGE
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename="+ sourceFileUri + "" + lineEnd);
                dos.writeBytes(lineEnd);

                Log.i("immmm22", "" + dos);

                // create a buffer of  maximum size
                bytesAvailable = fileInputStream.available();

                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {

                    //  Toast.makeText(this,": while", Toast.LENGTH_LONG).show();

                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }

                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                Log.i("immmm33", "" + dos);

                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile", "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode);

                //     Toast.makeText(getApplicationContext(), "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode,
                //         Toast.LENGTH_SHORT).show();

                if(serverResponseCode == 200){


                    //        Toast.makeText(context, "File Upload Complete.",
                    //           Toast.LENGTH_SHORT).show();

                }

                //close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {


                ex.printStackTrace();


                //  Toast.makeText(context, "MalformedURLException",
                //       Toast.LENGTH_SHORT).show();


                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {


                e.printStackTrace();



                //    Toast.makeText(context, " Exception : try again ! ",
                //     Toast.LENGTH_SHORT).show();

               // Log.i("Upload file to server Exception", "Exception : " + e.getMessage());
            }

            return serverResponseCode;

        } // End else block
    }

通过使用这个我能够上传图像到服务器。但是在服务器端没有收到文本。但使用Fidler应用程序到Web API的http post请求上传图像和文本?这个发送数据有什么问题吗?请提前帮助我

更新

现在我在服务器上收到了错误

System.IO.IOException: Error writing MIME multipart body part to output stream. ---> System.InvalidOperationException: The stream provider of type 'MultipartFormDataStreamProvider' threw an exception. ---> System.InvalidOperationException: Did not find required 'Content-Disposition' header field in MIME multipart body part.
   at System.Net.Http.MultipartFormDataStreamProviderHelper.IsFileContent(HttpContent parent, HttpContentHeaders headers)
   at System.Net.Http.MultipartFormDataStreamProvider.GetStream(HttpContent parent, HttpContentHeaders headers)
   at System.Net.Http.MimeBodyPart.GetOutputStream()
   --- End of inner exception stack trace ---
   at System.Net.Http.MimeBodyPart.GetOutputStream()
   at System.Net.Http.MimeBodyPart.<WriteSegment>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.Http.HttpContentMultipartExtensions.<MultipartReadAsync>d__8.MoveNext()
   --- End of inner exception stack trace ---
   at System.Net.Http.HttpContentMultipartExtensions.<MultipartReadAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Net.Http.HttpContentMultipartExtensions.<ReadAsMultipartAsync>d__0`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at WebApplication.Areas.Json.Controllers.TravelClaimsController.<PostFormData>d__2.MoveNext()

1 个答案:

答案 0 :(得分:0)

我已经使用此方法上传多部分请求(二进制数据和文本)

public class HttpClient {

...

方法是:

    public void connectForMultipart() throws Exception {
        con = (HttpURLConnection) ( new URL(url)).openConnection();
        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        con.connect();
        os = con.getOutputStream();
    }

public void addFormPart(String paramName, String value) throws Exception {
     writeParamData(paramName, value);
}

private void writeParamData(String paramName, String value) throws Exception {
            os.write( (delimiter + boundary + "\r\n").getBytes());
            os.write( "Content-Type: text/plain\r\n".getBytes());
            os.write( ("Content-Disposition: form-data; name=\"" + paramName + "\"\r\n").getBytes());;
            os.write( ("\r\n" + value + "\r\n").getBytes());

    }

其中

private String delimiter = "--";
private String boundary =  "SwA"+Long.toString(System.currentTimeMillis())+"SwA";



 The binary data (the image or something like that)



 public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
        os.write( (delimiter + boundary + "\r\n").getBytes());
        os.write( ("Content-Disposition: form-data; name=\"" + paramName +  "\"; filename=\"" + fileName + "\"\r\n"  ).getBytes());
        os.write( ("Content-Type: application/octet-stream\r\n"  ).getBytes());
        os.write( ("Content-Transfer-Encoding: binary\r\n"  ).getBytes());
        os.write("\r\n".getBytes());

        os.write(data);

        os.write("\r\n".getBytes());
    }

当您调用HttpClient时,您需要添加部分:

HttpClient client = new HttpClient(url);
 client.connectForMultipart();
 client.addFormPart("param1", param1);
 client.addFormPart("param2", param2);
 client.addFilePart("file", "logo.png", baos.toByteArray());
 client.finishMultipart();

public void finishMultipart() throws Exception {
        os.write( (delimiter + boundary + delimiter + "\r\n").getBytes());
}

希望它对你有所帮助。要了解更多信息,请查看我的blog post