2016-11-04 3 views
0

일부 데이터를 REST API에 보내려고합니다. API 문서는 Patch를 사용해야하며 JSON으로 데이터를 제공해야한다고 알려줍니다. API는 또한 oAuth 2.0을 호출해야하므로 액세스 토큰을 먼저 가져 와서 api url 호출에 추가합니다. 나는 말한다 .GetResonse에 오류가 발생, "(400) 잘못된 요청"을 try 블록에서HttpWebRequest PATCH 메서드와 JSON이 잘못된 요청을 제공합니다.

public MyResponse HttpPatch(
     string url, 
     string content, 
     Dictionary<string, string> headers, 
     string contentType = "application/json") 
    { 

     ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 

     var request = (HttpWebRequest)WebRequest.Create(Uri.EscapeUriString(url)); 
     if (request == null) 
      throw new ApplicationException(string.Format("Could not create the httprequest from the url:{0}", url)); 

     request.Method = "PATCH"; 
     foreach (var item in headers) 
      request.Headers.Add(item.Key, item.Value); 

     UTF8Encoding encoding = new UTF8Encoding(); 
     var byteArray = Encoding.ASCII.GetBytes(content); 

     request.ContentLength = byteArray.Length; 
     request.ContentType = contentType; 

     Stream dataStream = request.GetRequestStream(); 
     dataStream.Write(byteArray, 0, byteArray.Length); 
     dataStream.Close(); 

     try 
     { 
      var response = (HttpWebResponse)request.GetResponse(); 
      return new MyResponse(response); 
     } 
     catch (WebException ex) 
     { 
      HttpWebResponse errorResponse = (HttpWebResponse)ex.Response; 
      return new MyResponse(errorResponse); 
     } 
    } 

:

나는 다음과 같은 코드가 있습니다.

URL = https://api.myserver.com/v1/users/1234?access_token=my_access_token

내용 = LANG = FR & 국적 = FR & 국가 = (myserver를하고 my_access_token 내 코드에서 실제 값이) FR & FIRST_NAME = 존 & : 값은 나는 방법 제공 { "인증", "apiKey에의 참고 MyUser :의 mykey"} 한 요소와 LAST_NAME = 미상

헤더 = 사전 (참고 MyUser와의 mykey 내 코드에 실제 값이)

contentType = "application/json"

"잘못된 요청"오류를 설명 할 수있는 것이 누락되었습니다. 이 오류의 원인은 무엇입니까?

내가 사용하는 액세스 토큰이 정확합니다. 끝점 URL이 정확합니다. 메쏘드의 "PATCH"값에 대해 잘 모르겠습니다. 어떻게 할 수 있습니까? MSDN 설명서는 가능한 값이 언급하지 않기 때문에 : https://msdn.microsoft.com/nl-be/library/system.net.httpwebrequest.method(v=vs.110).aspx

내 머리를 당기고 2 일 동안 어려움을 겪고 지금은 너무 잘하면 누군가가 넣어 나에게 줘 좋은 포인터의 빛을 보여줄 수, 작업 전화를 얻기 위해 나 옳은 길에?

답변

0

결국 작동합니다. json을 제공하지 않았기 때문에 컨텐츠 유형이 잘못되었습니다. "application/x-www-form-urlencoded"로 변경하고 메소드의 PATCH 값을 유지 한 후 이제 작동합니다.

관련 문제