调用REST Web服务时不支持的媒体类型

时间:2013-09-05 20:33:42

标签: c# rest

我正在调用一个REST Web服务,它给了我这个文档

HTTP Method: POST 
Path: /commit/{path}/add-node  
Response Status 200, 302, 403, 404, 409, 503 

Form Parameters 
    - name : attribute name 
    - message : commit message 

基于此文档。我写了以下C#代码。

  string restUrl = webServiceurl + "/commit/" + path + "/add-node";
  restUrl = restUrl + "?name=" + nodeName + "&message=" + commitMessage;
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restUrl);
  request.Method = "POST";
  request.ContentType = @"application/json";
    using (WebResponse response = request.GetResponse()) {
      using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
        output = reader.ReadToEnd();
      }
    }

我也试过

  string restUrl = webServiceurl + "/commit/" + path + "/add-node";
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restUrl);
  request.Method = "POST";
  request.ContentType = @"application/json";
  var param = new { name = nodeName, message = commitMessage };
  Stream reqStream = null;
  string output = null;
  try {

     byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(
                        JsonConvert.SerializeObject(param)
                    );

    request.ContentLength = buffer.Length;
    reqStream = request.GetRequestStream();
    reqStream.Write(buffer, 0, buffer.Length);

    using (WebResponse response = request.GetResponse()) {
      using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
        output = reader.ReadToEnd();
      }
    }
  } catch (Exception ex) {
      .....
  }

不幸的是,在这两种情况下,我都得到415 Unsupported Media Type。我的代码出了什么问题?

Web服务是一种用Java编写的基于REST的Web服务。

1 个答案:

答案 0 :(得分:2)

根据this forum post,Java Web服务可能不支持ContentType属性。你确定它接受application / json吗?