【问题标题】:httpmultipart request for this webservice getdata code in c# with android在 c# 中使用 android 对此 webservice getdata 代码的 httpmultipart 请求
【发布时间】:2012-08-24 09:53:44
【问题描述】:

您好,我有一个带有此代码的网络服务 IIS:

    // Implements multipart/form-data POST in C# http://www.ietf.org/rfc/rfc2388.txt
// http://www.briangrinstead.com/blog/multipart-form-post-in-c
public static class FormUpload
{
    private static readonly Encoding encoding = Encoding.UTF8;
    public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
    {
        string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
        string contentType = "multipart/form-data; boundary=" + formDataBoundary;

        byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);

        return PostForm(postUrl, userAgent, contentType, formData);
    }
    private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
    {
        HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;

        if (request == null)
        {
            throw new NullReferenceException("request is not a http request");
        }

        // Set up the request properties.
        request.Method = "POST";
        request.ContentType = contentType;
        request.UserAgent = userAgent;
        request.CookieContainer = new CookieContainer();
        request.ContentLength = formData.Length;

        // You could add authentication here as well if needed:
        // request.PreAuthenticate = true;
        // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
        // request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("username" + ":" + "password")));

        // Send the form data to the request.
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(formData, 0, formData.Length);
            requestStream.Close();
        }

        return request.GetResponse() as HttpWebResponse;
    }

    private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
    {
        Stream formDataStream = new System.IO.MemoryStream();
        bool needsCLRF = false;

        foreach (var param in postParameters)
        {
            // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.
            // Skip it on the first parameter, add it to subsequent parameters.
            if (needsCLRF)
                formDataStream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));

            needsCLRF = true;

            if (param.Value is FileParameter)
            {
                FileParameter fileToUpload = (FileParameter)param.Value;

                // Add just the first part of this param, since we will write the file data directly to the Stream
                string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
                    boundary,
                    param.Key,
                    fileToUpload.FileName ?? param.Key,
                    fileToUpload.ContentType ?? "application/octet-stream");

                formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));

                // Write the file data directly to the Stream, rather than serializing it to a string.
                formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
            }
            else
            {
                string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}",
                    boundary,
                    param.Key,
                    param.Value);
                formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));
            }
        }

        // Add the end of the request.  Start with a newline
        string footer = "\r\n--" + boundary + "--\r\n";
        formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));

        // Dump the Stream into a byte[]
        formDataStream.Position = 0;
        byte[] formData = new byte[formDataStream.Length];
        formDataStream.Read(formData, 0, formData.Length);
        formDataStream.Close();

        return formData;
    }

    public class FileParameter
    {
        public byte[] File { get; set; }
        public string FileName { get; set; }
        public string ContentType { get; set; }
        public FileParameter(byte[] file) : this(file, null) { }
        public FileParameter(byte[] file, string filename) : this(file, filename, null) { }
        public FileParameter(byte[] file, string filename, string contenttype)
        {
            File = file;
            FileName = filename;
            ContentType = contenttype;
        }
    }
}

从这里获取:Multipart forms from C# client

但是现在,在 mi android aplicattion 我有这个:

HttpParams httpParameters = new BasicHttpParams();
            int timeoutConnection = 300000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            int timeoutSocket = 300000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
            HttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpPost postRequest = new HttpPost("http://172.21.1.87:9999/Service1.svc");
            ByteArrayBody bab = new ByteArrayBody(ficheroAEnviar, "prueba.jpg");
            MultipartEntity reqEntity = new MultipartEntity();            
            postRequest.addHeader("Content-Type", " multipart/form-data");
            reqEntity.addPart("Dictionary", new FileBody(new File(fileUri.toString(), "application/zip")));
            reqEntity.addPart("boundary", new StringBody("envio"));
            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();
            postRequest.getAllHeaders();

            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());
        }
    }

但它返回错误请求 400 错误。我可以使用 c# 代码通过 android 上传多方文件还是需要对某些代码进行任何更改?

谁有一个例子 en c# 和 android 来做这个?用于上传大约 10 或 15 MB 的视频。

谢谢

【问题讨论】:

    标签: c# android web-services httpclient multipartentity


    【解决方案1】:

    不要使用多部分实体,而是使用在这里定义边界很容易 试试看

    HttpURLConnection connection = null;
     DataOutputStream outputStream = null;
    DataInputStream inputStream = null;
    
       String pathToOurFile = "/data/file_to_send.mp3";
        String urlServer = "http://192.168.1.1/handle_upload.php";
      String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";
    
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;
    
    try
    {
    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
    
    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();
    
     // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    
     // Enable POST method
    connection.setRequestMethod("POST");
    
      connection.setRequestProperty("Connection", "Keep-Alive");
      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(lineEnd);
    
     bytesAvailable = fileInputStream.available();
       bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];
    
    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    
    while (bytesRead > 0)
     {
    outputStream.write(buffer, 0, bufferSize);
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }
    
    outputStream.writeBytes(lineEnd);
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    
    // Responses from the server (code and message)
    serverResponseCode = connection.getResponseCode();
    serverResponseMessage = connection.getResponseMessage();
    
    fileInputStream.close();
    outputStream.flush();
    outputStream.close();
    }
    catch (Exception ex)
    {
    //Exception handling
    }
    

    由拉菲尔提供

    【讨论】:

    • 但是我需要使用网络服务 iis,这不适合我,不是吗?
    • 多部分帖子是常见的东西,在那个伙伴的 iis nd Apache 中没有差异
    • 但是我怎样才能从172.21.1.87:9999/Service1.svc,SOAP¿调用UploadFile方法¿
    • 尝试在 url 空间中提供它可能会起作用它
    • 对不起,伙计,我在这里不处理 asp,所以很难尝试搜索,但我认为在你的帖子中你也没有使用肥皂信封直接发布
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多