2012-05-05 4 views
0

WebRequest를 사용하여 콘솔 응용 프로그램을 통해 조직의 서버에 파일을 게시합니다. 온라인에서 몇 가지 연구를 한 후에, 나는 아래의 코드를 찾을 수 있었다.WebRequest POST는 "원격 서버에서 오류를 반환했습니다 : (405) 메서드가 허용되지 않았습니다."

try 
{ 
    RegisterString("Uploading encrypted file to server....Please wait!!"); 
    string url = @"http://localhost:3333/MySite/" 
    string filepath = @"C:\test.txt"; 
    WebRequest request = WebRequest.Create(url); 
    request.Method = "POST"; 
    request.PreAuthenticate = true; 
    request.Credentials = new NetworkCredential(ftp_username, ftp_password); 
    byte[] byteArray = Encoding.UTF8.GetBytes(filePath); 
    request.ContentType = "application/x-www-form-urlencoded"; 
    request.ContentLength = byteArray.Length; 


    //Here is the Business end of the code... 
    Stream dataStream = request.GetRequestStream(); 
    dataStream.Write(byteArray, 0, byteArray.Length); 
    dataStream.Close(); 
    //and here is the response. 
    WebResponse response = request.GetResponse(); 

    Console.WriteLine(((HttpWebResponse)response).StatusDescription); 
    dataStream = response.GetResponseStream(); 
    StreamReader reader = new StreamReader(dataStream); 
    string responseFromServer = reader.ReadToEnd(); 
    Console.WriteLine(responseFromServer); 
    reader.Close(); 
    dataStream.Close(); 
    response.Close(); 

    RegisterString("File uploaded sucessfully");     

    try 
    { 
     //Delete file after transmission 
     File.Delete(filePath); 
    } 
    catch (Exception ex) 
    { 
     RegisterString(ex.Message); 
    } 

    WriteToLog("End"); 
    System.Threading.Thread.Sleep(5000); 
} 
catch (Exception ex) 
{ 
    RegisterString(ex.Message); 
    System.Threading.Thread.Sleep(5000); 
    WriteToLog("End"); 
} 

그러나 "405 Method Not Allowed"예외가 발생합니다. 내가 누락 된 것이 있습니까?

+0

응답이 * Method *에 대해 명시 적으로 불평하므로 - 이미 "request.Method ="GET ";("POST "대신에) 시도 했습니까? – Filburt

+0

작업의 다른 끝에서 코드와 더 관련이 있다고 생각하지만 바이너리 데이터가있는 HTTP POST의 MIME 유형은 일반적으로'multipart/form-data'입니다. 게시하고있는 서비스가 표준 형식의 양식 게시를 기대하지 않고 있지만 콘텐츠 유형이 'application/x-www-form'이 아닌 실제 데이터 형식이되어야한다고 생각합니다. -urlencoded'입니다. –

+0

한 번 contenttype을 multipart/form-data로 변경했습니다. 다른 오류 (404) 파일을 찾을 수 없습니다.) – Jay

답변

0

ftp 서버입니까? 그렇다면 메소드는 POST가 아니라 PUT이어야합니다.

+0

웹 서버 ... 그리고 put을 사용하고 있습니다. 다음은 샘플입니다. WebClient client = new WebClient(); CredentialCache credCache = new CredentialCache(); credCache.Add (새 Uri (ftp_url + filePath), "기본", ) 새 NetworkCredential (ftp_username, ftp_password, "africa"))); client.Credentials = credCache; Uri 주소 = 새 Uri (@ftp_url + filePath); WriteToLog (@ftp_url + filePath); 바이트 [] arrReturn = client.UploadFile (주소, "PUT", filePath); – Jay

관련 문제