Java Android对web api的多部分请求未获取与请求关联的文本

Java Android对web api的多部分请求未获取与请求关联的文本,java,android,api,http,Java,Android,Api,Http,你好,我在安卓工作。我想将多部分数据发送到asp.net web api。我有一个json数据和多个图像 public int uploadFile(Context context,ArrayList<String> sourceFileUri,String json,String url1) { // Toast.makeText(this,"uploading...", Toast.LENGTH_SHORT).show(); Stri

你好,我在安卓工作。我想将多部分数据发送到asp.net web api。我有一个json数据和多个图像

 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
    }
public int uploadFile(上下文上下文、ArrayList sourceFileUri、字符串json、字符串url1){
//Toast.makeText(这是“上载…”,Toast.LENGTH_SHORT.show();
StrictMode.ThreadPolicy策略=新建
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(策略);
Log.i(“uploadimage”,“sourceFileUri.get(0));
HttpURLConnection conn=null;
DataOutputStream dos=null;
字符串lineEnd=“\r\n”;
字符串双连字符=“--”;
字符串边界=“*******”;
int字节读取,字节可用,缓冲区大小;
字节[]缓冲区;
int maxBufferSize=1*1024*1024;
File sourceFile=新文件(android.os.Environment.getExternalStorageDirectory()+“/TrackonPro”,sourceFileUri.get(0));
如果(!sourceFile.isFile()){
Log.i(“uploadFile”,“源文件不存在:“+sourceFileUri”);
返回0;
}
其他的
{
//Toast.makeText(这是“找到的路径:”+imagePath,Toast.LENGTH_LONG.show();
试一试{
//Toast.makeText(这是“try…”,Toast.LENGTH_LONG.show();
//打开到Servlet的URL连接
FileInputStream FileInputStream=新的FileInputStream(sourceFile);
URL=新URL(url1);
//打开到URL的HTTP连接
conn=(HttpURLConnection)url.openConnection();
conn.setDoInput(true);//允许输入
conn.setDoOutput(true);//允许输出
conn.setUseCaches(false);//不要使用缓存副本
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“连接”、“保持活动”);
conn.setRequestProperty(“ENCTYPE”、“多部分/表单数据”);
conn.setRequestProperty(“内容类型”、“多部分/表单数据;边界=“+boundary”);
//Toast.makeText(这个,“url:+url,Toast.LENGTH_LONG).show();
dos=新的DataOutputStream(conn.getOutputStream());
写字节(两个连字符+边界+行结束);
//JSON字符串
writeBytes(“内容处置:表单数据;名称=\“sanu\”);
dos.writeBytes(lineEnd);
dos.writeBytes(json);
dos.writeBytes(lineEnd);
写字节(两个连字符+边界+行结束);
Log.i(“immm11”和“+dos”);
//形象
写字节(两个连字符+边界+行结束);
dos.writeBytes(“内容处置:表单数据;名称=\”上传的文件\“文件名=”+sourceFileUri+“”+lineEnd);
dos.writeBytes(lineEnd);
Log.i(“immm22”和“+dos”);
//创建最大大小的缓冲区
bytesAvailable=fileInputStream.available();
bufferSize=Math.min(字节可用,maxBufferSize);
buffer=新字节[bufferSize];
//读取文件并将其写入表单。。。
bytesRead=fileInputStream.read(缓冲区,0,缓冲区大小);
而(字节读取>0){
//Toast.makeText(这个“:while”,Toast.LENGTH_LONG.show();
写入(缓冲区,0,缓冲区大小);
bytesAvailable=fileInputStream.available();
bufferSize=Math.min(字节可用,maxBufferSize);
bytesRead=fileInputStream.read(缓冲区,0,缓冲区大小);
}
//发送文件数据后所需的多部分表单数据。。。
dos.writeBytes(lineEnd);
写字节(两个连字符+边界+两个连字符+行结束);
Log.i(“immm33”和“+dos”);
//来自服务器的响应(代码和消息)
serverResponseCode=conn.getResponseCode();
字符串serverResponseMessage=conn.getResponseMessage();
Log.i(“uploadFile”,“HTTP响应为:“+serverResponseMessage+”:“+serverResponseCode”);
//Toast.makeText(getApplicationContext(),“HTTP响应为:“+serverResponseMessage+”:“+serverResponseCode,
//吐司。长度(短)。show();
如果(服务器响应代码==200){
//Toast.makeText(上下文,“文件上载完成”,
//吐司。长度(短)。show();
}
//关闭溪流//
fileInputStream.close();
dos.flush();
dos.close();
}捕获(格式错误){
例如printStackTrace();
//Toast.makeText(上下文,“MalformedURLException”,
//吐司。长度(短)。show();
Log.e(“将文件上载到服务器”,“错误:+ex.getMessage(),ex”);
}捕获(例外e){
e、 printStackTrace();
//Toast.makeText(上下文,“异常:重试!”,
//吐司。长度(短)。show();
//i(“上传文件到服务器异常”,“异常:+e.getMessage());
}
返回服务器响应代码;
}//结束else块
}
通过使用这个,我可以将图片上传到服务器,但服务器端并没有收到文本。但是http post请求使用Fidler应用程序将图像和文本上传到web API?这个发送数据有问题吗。请先帮我谢谢

更新

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

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()
System.IO.IOException:写入MIME多部分正文时出错
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 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());
}