如何使用HttpWebRequest上传文件,知道我想通过相同的请求传递其他信息?
我要传递给请求的对象:
public class product
{
public int Id { get; set; }
public string Name { get; set; }
public string DescriptionFilePath { get; set; }
}
请求网址:http://api.mydomain.com/upload
谢谢!
答案 0 :(得分:0)
尝试
public HttpWebResponse SendRequest(Product product){
//create the request with the url
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.mydomain.com/upload");
//set the put method
request.method = "PUT";
//serialize the product
JavascriptSerializer serializer = new JavascriptSerializer();
var body = serializer.Setialize(product);
//write the serialized product to the request
using(StreamWriter writer = new StreamWriter(request.GetRequestStream())){
writer.write(body);
}
//execute the request and return the response
return (HttpWebResponse) request.getResponse();
}
发送请求。 如果您需要检索响应数据
public string RetrieveResponseData(HttpWebResponse response){
var result;
using StreamReader reader = new StreamReader(response.GetResponseStream()){
result = reader.ReadToEnd();
}
return result;
}