我制作了一个包装器,用于向Web服务器发送数据和从Web服务器接收数据。到目前为止它的工作原理但是当我尝试使用它来发送带有文件字节数组(pdf或word doc)的内容时,它会失败并向我提供消息 Request-URI to long
这是包装器的代码:
public class CallWebService
{
public enum Methods
{
GET = 1,
POST = 2,
PUT = 3,
DELETE = 4
}
//public TResult ExecutionResult { get; set; }
public string WebServiceURL { get; set; }
public Methods Method { get; set; }
public CallWebService(string sWebServiceUrl)
{
this.WebServiceURL = sWebServiceUrl;
}
public TResult Execute<TResult>(string sCommand, Methods mMethod)
{
return Execute<TResult, string>(sCommand, mMethod, null);
}
public TResult Execute<TResult, TParam>(string sCommand, Methods mMethod, TParam parameter)
{
TResult executionResult = default(TResult);
string requestUriString = "";
try
{
if (this.WebServiceURL != null)
{
requestUriString = Path.Combine(this.WebServiceURL, sCommand);
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
jsonSerializer.MaxJsonLength = int.MaxValue;
string jsonParameter = null;
if (parameter != null)
{
jsonParameter = jsonSerializer.Serialize(parameter);
requestUriString += "?" + jsonParameter;
}
HttpWebRequest req = WebRequest.Create(requestUriString) as HttpWebRequest;
req.KeepAlive = false;
req.Method = mMethod.ToString().ToUpper();
Stream dataStream;
if (("POST,PUT").Split(',').Contains(mMethod.ToString().ToUpper()))
{
if (jsonParameter != null && jsonParameter.ToString().Length > 0)
{
byte[] byteArray = Encoding.UTF8.GetBytes(jsonParameter);
// Set the ContentType property of the WebRequest.
req.ContentType = "application/json; charset=utf-8";
// Set the ContentLength property of the WebRequest.
req.ContentLength = byteArray.Length;
// Get the request stream.
dataStream = req.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
}
}
// Get the response.
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
executionResult = jsonSerializer.Deserialize<TResult>(responseFromServer);
}
else
{
throw new Exception("WebServiceURL not provided. Please initialize the object first.");
}
}
catch (Exception ex)
{
//To Do
}
return executionResult;
}
}
}
感谢任何帮助