尝试编写一个工具,通过REST API从服务器下载.zip文件。 它的工作没有SOAP-UI的任何问题,但我的工具不想下载任何文件。
始终收到此错误:
无法使用此动词类型发送内容正文。
我的POST-Requests工作正常,但GET-Requests会产生问题。我认为我的Webrequest-Header存在问题。
身份验证必须如下所示:
承载“访问令牌”
这是我的代码:
class RestProvider
{
protected string method;
protected string endpoint;
protected string resource;
protected string parameters;
public RestProvider(string method, string endpoint, string resource, string parameters)
{
this.method = method;
this.endpoint = endpoint;
this.resource = resource;
this.parameters = parameters;
}
public string GetResponse()
{
string resultString = string.Empty;
ASCIIEncoding enc = new ASCIIEncoding();
byte[] paramData = enc.GetBytes(parameters);
if (this.method == "post")
{
try
{
WebRequest request = WebRequest.Create(this.endpoint + this.resource);
request.Method = this.method;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = paramData.Length;
Stream stream = request.GetRequestStream();
stream.Write(paramData, 0, paramData.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
resultString = sr.ReadToEnd();
sr.Close();
stream.Close();
}
catch(Exception ex)
{
resultString = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
}
else if(this.method == "get")
{
try
{
WebRequest request = WebRequest.Create(this.endpoint + this.resource);
request.Headers["Authorization"] = "Bearer " + Convert.ToBase64String(Encoding.Default.GetBytes(this.parameters));
request.Method = this.method;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = paramData.Length;
Stream stream = request.GetRequestStream();
stream.Write(paramData, 0, paramData.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
resultString = sr.ReadToEnd();
sr.Close();
stream.Close();
}
catch (Exception ex)
{
resultString = "{\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
}
return resultString;
}
}
有什么想法吗?