405 - Method Not Allowed HttpWebRequest

前端 未结 3 859
萌比男神i
萌比男神i 2021-01-25 03:54

I have a problem when trying to send a POST request. The sending method looks like this:

Public Sub SendXML(ByVal file As String)
    Dim reader As          


        
3条回答
  •  灰色年华
    2021-01-25 04:48

    Your POST appears to be completely invalid. POST data is supposed to be encoded (ie, as multipart/form-data) and use correct content-type (ie, application/x-www-form-urlencoded) with proper encoding and boundaries etc. You are just sending the server a lump of text and I'm not surprised it flips out.

    I'm not 100% sure what VB is doing behind the scenes but this MSDN page suggests you need to set the content-type to a supported method and you probably need Content-Disposition: form-data in your headers as well. I found an example that does this and adds the MIME boundaries:

    string FileData = "this is test file data\r\n"; // test data to send.
    StringBuilder DataString = new StringBuilder();
    DataString.Append(dataBoundary + "\r\n");
    //This sends the viewstate info
    DataString.Append("Content-Disposition: form-data; name=" + HiddenValue
    + "\r\n"
    + dataBoundary + "\r\n");
    DataString.Append("Content-Disposition: form-data; name=" + "\"" +
    "File1" +
    "\"" +
    "; filename=" + "\"" + "TestFile3.txt" + "\"" + "\r\n");
    DataString.Append("Content-Type: text/plain\r\n\r\n");
    DataString.Append(FileData);
    DataString.Append(dataBoundary + "\r\n");
    DataString.Append("Content-Disposition: form-data; name=" + "\"" +
    "Submit1" +
    "\"" + "\r\n\r\n" + "Upload\r\n" + dataBoundary + "--\r\n");
    

    That example emulates a file field upload.

    For a simpler version you can use request.ContentType = "application/x-www-form-urlencoded" with URL-encoded data like: Dim postData As String = "myURL=http%3A%2F%2Fexample.com%2Findex.php". Note that the format is key=value and the data must be URL-encoded first.

    I'm not sure what exactly you need though because a lot depends on what the remote server actually expects for the form and field names. It also depends wether the server is actually following the relevant HTML standards and RFCs. Do you have a working HTML form to use as a guide for what the server expects?

提交回复
热议问题