2016-12-18 3 views
1

모바일에서 asp 서버로 파일을 업로드해야합니다. 이 기능은 클라이언트가 업로드 서버용 프록시를 추가 할 때까지 작동합니다.Android 게시물 요청이 잘 렸습니다

iOS에 내가 NSMutableURLRequest을 사용하고 내가 HttpUrlConnection 사용 android에 데이터로 HttpBody에 작업이

let request = NSMutableURLRequest(URL:NSURL(string:urlString)!) 
request.HTTPBody = uploader.createBodyWithParameters() 
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {...} 

,

을 파일을 추가, 내가 요청은 모든 데이터가 보내, 잘 렸습니다 발견 OutputStream에 의해 사라집니다.

다음
URL connectURL = new URL(serverURL); 
      HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection(); 

      conn.setDoInput(true); // Allow Inputs 
      conn.setDoOutput(true); // Allow Outputs 
      conn.setUseCaches(false); 
      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("Connection", "Keep-Alive"); 
      conn.setRequestProperty("Accept", "*/*"); 
      conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); 
      conn.setRequestProperty("Accept-Language", "en-usa"); 

      conn.addRequestProperty("Authorization", "Bearer " + uploader.accesstoken); 
      conn.setRequestProperty("Content-Type", 
        "multipart/form-data; boundary=" + boundary); 


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

      dos.writeBytes(twoHyphens + boundary + lineEnd); 
      dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" 
          + fileName +"\"" + lineEnd); 

      dos.writeBytes("Content-Type: "+"application/zip, application/octet-stream"+"\r\n\r\n"); 

      FileInputStream fileInputStream = new FileInputStream(new File(filePath+"/"+fileName)); 
      int bytesAvailable = fileInputStream.available(); 
      int maxBufferSize = 1024 * 1024; 

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

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

      while (bytesRead > 0) { 

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

입니다 IOS 요청 데이터

POST /Upload.ashx HTTP/1.1 
Connection: keep-alive 
Content-Length: 6998 
Content-Type: multipart/form-data; boundary=Boundary-417BEF5E-9840-4369-B397-C5BA87C25D9E 
Accept: */* 
Accept-Encoding: gzip, deflate 
Accept-Language: en-usa 
Authorization: ... 
Host: 192.168.1.5 
User-Agent: Apploader/11 CFNetwork/758.2.8 Darwin/15.6.0 

--Boundary-417BEF5E-9840-4369-B397-C5BA87C25D9E 
Content-Disposition: form-data; name="file"; filename="..." 
Content-Type: application/zip, application/octet-stream 

.......  
--Boundary-417BEF5E-9840-4369-B397-C5BA87C25D9E-- 

안드로이드 끝 "사용자 에이전트 : 달빅/2.1.0 (리눅스, U, 안드로이드 6.0.1, SM-G925V 빌드/MMB29K)"

POST /AppLoader/Upload.ashx HTTP/1.1 
Connection: Keep-Alive 
Content-Length: 7464126 
Content-Type: multipart/form-data; boundary=Boundary-fc13ac98-53bf-4f3f-9a56-ddc4393d8719 
Accept-Encoding: gzip 
Authorization: Bearer .. 
Host: ... 
User-Agent: Dalvik/2.1.0 (Linux; U; Android 6.0.1; SM-G925V Build/MMB29K) 

프록시가 추가되지 않은 상태에서 업로드 기능이 제대로 작동하지 않을 때 발생하는 문제입니다. 내 질문은 아이폰 OS와 안드로이드 사이에 다른 안드로이드 업로드 실패, 어떻게 이것을 해결하기 위해 무엇입니까? 여기

프록시 코드 :

using Client.Proxy.Controllers; 
using Client.Utilites; 
using System; 
using System.Diagnostics; 
using System.IO; 
using System.Net; 
using System.Net.Http; 
using System.Threading.Tasks; 
using System.Web; 
using System.Web.Http; 

namespace Proxy.Controllers 
{ 
    [RoutePrefix("Loader")] 
    public class AppLoaderController : BaseApiController 
    { 
     public AppLoaderController() 
     { 
      base.defaultServiceProxyName = "Loader"; 
     } 
     [HttpPost] 
     [ActionName("Upload.ashx")] 
     public HttpResponseMessage Upload() 
     { 
      HttpResponseMessage result = new HttpResponseMessage(); 
      try 
      { 
       LoggingUtilities.WriteLog("Upload Started", TraceEventType.Verbose); 
       var connector = GetConnectorProxyURI("AppLoaderReceiver").ToString();     
       LoggingUtilities.WriteLog(string.Format("Connector: {0}", connector), TraceEventType.Verbose); 

       string requestUri = string.Format("{0}/Upload.ashx", connector.Replace("/AppLoader", "/")); 
       LoggingUtilities.WriteLog(string.Format("requestUri: {0}", requestUri), TraceEventType.Verbose); 

       MultipartFormDataContent content = new MultipartFormDataContent(); 
       byte[] buffer = null; 
       try 
       { 
        HttpPostedFile file; 
        string requestFileName = string.Format("request-{0:yyyy-MM-dd_hh-mm-ss-tt}.txt", DateTime.Now); 
        LoggingUtilities.WriteLog(string.Format("log request to file."), TraceEventType.Verbose); 
        HttpContext.Current.Request.SaveAs(string.Format(@"c:\temp\{0}", requestFileName), true); 
        LoggingUtilities.WriteLog(string.Format("About to check Current.Request.Files.Count"), TraceEventType.Verbose); 
        if (HttpContext.Current.Request.Files.Count > 0) 
        { 
         file = HttpContext.Current.Request.Files[0]; 
         LoggingUtilities.WriteLog(string.Format("file.ContentLength ={0}", file.ContentLength), TraceEventType.Verbose); 
         using (BinaryReader reader = new BinaryReader(file.InputStream)) 
         { 
          buffer = reader.ReadBytes(file.ContentLength); 
         } 
         LoggingUtilities.WriteLog("Got FileData", TraceEventType.Verbose); 
         content.Add(new ByteArrayContent(buffer, 0, buffer.Length), "application/zip", file.FileName); 
         LoggingUtilities.WriteLog("Got ByteArrayContent", TraceEventType.Verbose); 
         string fileName = ""; 
         fileName = HttpContext.Current.Request.Files[0].FileName; 
         LoggingUtilities.WriteLog(string.Format("Filename= {0}", fileName), TraceEventType.Verbose); 
         if (string.IsNullOrEmpty(fileName)) 
         { 
          TimeSpan span = (TimeSpan)(DateTime.UtcNow - new DateTime(0x7b1, 1, 1)); 
          string str3 = span.TotalMilliseconds.ToString().Substring(0, 13); 
          fileName = string.Format("*.zip", str3); 
         } 
         content.Add(new StringContent(fileName), "FILE_NAME"); 
         Task<HttpResponseMessage> task1 = new HttpClient().PostAsync(requestUri, content); 
         task1.Wait(); 
         result = task1.Result; 
        } 
        else 
        { 
         result = new HttpResponseMessage(HttpStatusCode.BadRequest); 
        } 
       } 
       catch (Exception exception) 
       { 
        result = new HttpResponseMessage(HttpStatusCode.BadRequest); 
       } 
      } 
      catch (Exception exception2) 
      { 
       result = new HttpResponseMessage(HttpStatusCode.BadRequest); 
      } 
      return result; 
     } 
    } 
} 

답변

0

이 답변으로 당신을 도울 수 How do I make HttpURLConnection use a proxy?; 안드로이드에는 발리, aysnchttp, okhttp와 같은 많은 http 도구가 있습니다 ... 원래 HttpUrlConnection 대신 그 중 하나를 선택할 수 있습니다. 코드에 로그 인쇄를 추가하고 로그를 제공 할 수 있다면이 문제에 대해 더 많이 알 수 있습니다.

0

감사합니다. Chris와 Gao. 나는 제거하여 안드로이드에 전송되기 전에 gzip을하는

conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); 

어떤 효과 서버 변환 문자 메시지를이 문제를 해결했습니다.

conn.getContentLength()에서 -1을 얻었을 때 또 다른 문제가 발생했습니다. 콘텐츠가 비어 있다고 생각했지만 요청에 알 수없는 콘텐츠 길이가있는 것입니다. 여전히 conn.getInputStream()에서 내용을 읽을 수 있습니다.

관련 문제