2016-06-21 4 views
2

Ich versuche, eine HTTP-POST-Anfrage zu senden, um Kontaktinformationen mithilfe ihrer API an einen Mail Exchange-Server zu senden (Erstellung eines neuen Abonnenten). Ich verwende Java und java.util.HttpURLConnection.Fehler beim Senden einer POST-Anfrage, die von OAuth authentifiziert wurde, mithilfe des Wegweisers

Wenn ich versuche, die Verbindung zu signieren, bekomme ich eine Null-Referenz Ausnahme. Wenn ich versuche, die Verbindung vor dem Hinzufügen der setRequestProperty Header zu signieren, erhalte ich eine ungültige Signatur Antwort vom Server.

Die Verwendung einer GET-Anforderung mit derselben allgemeinen Prozedur funktioniert - was bedeutet, dass, soweit ich weiß, meine Signiermethode (und Schlüsselwerte usw.) in Ordnung ist.

Der Dienst, den ich verwenden möchte, hat eine Art von "SDK" zur Verfügung, in .NET geschrieben. Ich habe nicht versucht, es zu benutzen, aber ich glaube, es funktioniert (sie erklären es).

Ich versuchte, ihre Prozedur zu replizieren. Im Folgenden finden Sie meinen Code finden, folgen von ihnen:

private static HttpURLConnection createAndSendOAuthPostRequestWithParams() throws MalformedURLException, IOException, Exception { 

    String url = "http://apisdomain/v1.0/lists/354467/subscribers"; 

    // Here I set up the values given by the provider (API's admin) which I removed from the example 
    String clientKey = ""; 
    String clientSecret = ""; 
    String userKey = ""; 
    String userSecret = ""; 

    String postData = "NAME=TestSubscriber&[email protected] 
    byte[] postBody = postData.getBytes("UTF-8"); 

    URL apiUrl = new URL(url); 
    HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();  

    connection.setRequestMethod("POST"); 
    connection.setRequestProperty("content-length", String.valueOf(postBody.length)); 
    connection.setRequestProperty("content-type", "application/x-www-form-urlencoded; charset=UTF-8"); 

    //OAuth 
    OAuthConsumer consumer = new DefaultOAuthConsumer (clientKey, clientSecret); 
    //consumer.setAdditionalParameters(parameters); 
    consumer.setTokenWithSecret(userKey, userSecret); 
    HttpRequest httpReq = consumer.sign(connection); //Where the exception occurs 

    if (!postBody.toString().isEmpty()) { 
     connection.setDoOutput(true); 

     try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { 
      outputStream.write(postBody); 
      outputStream.flush(); 
     } 
    } 

    return connection; 
} 

Von thier SDK:

using System.Text; 

namespace ResponderSDK 
{ 

    using OAuth; 
    using System; 
    using System.Collections.Generic; 
    using System.Net; 
    using System.IO; 

    class ResponderOAuth 
    { 

     /* Contains the last HTTP status code returned. */ 
     public HttpStatusCode http_code; 
     /* Contains the last API call. */ 
     public string url; 
     /* Set up the API root URL. */ 
     public string host = "http://api.responder.co.il/v1.0/"; 
     /* Set timeout default. */ 
     public int timeout = 3000; 
     /* Set connect timeout. */ 
     public int connect_timeout = 30; 
     /* Verify SSL Cert. */ 
     public bool ssl_verifypeer = false; 
     /* Response format. */ 
     public string format = "json"; 
     /* Contains the last HTTP headers returned. */ 
     public string http_info; 
     /* Set the useragent. */ 
     public string useragent = "ResponderOAuth v0.1-beta"; 

     /*debug info*/ 
     public string headers_string; 
     public string base_string; 
     public string post_string; 

     /* Signature */ 
     private OAuthSignatureMethod_HMAC_SHA1 signature; 
     /* OAuthConsumer */ 
     private OAuthConsumer consumer; 
     /* Token */ 
     private OAuthToken token; 


     public ResponderOAuth(string consumer_key, string consumer_secret, string oauth_token = null, string oauth_token_secret = null) 
     { 
      this.signature = new OAuthSignatureMethod_HMAC_SHA1(); 
      this.consumer = new OAuthConsumer(consumer_key, consumer_secret); 
      if (!String.IsNullOrEmpty(oauth_token) && !String.IsNullOrEmpty(oauth_token_secret)) 
      { 
       this.token = new OAuthToken(oauth_token, oauth_token_secret); 
      } 
      else 
      { 
       this.token = null; 
      } 
     } 

     public string http_request(string url, string method = "GET", ParametersArray parameters = null) 
     { 
      method = method.ToUpper(); 
      if (url.LastIndexOf("https://") != 0 && url.LastIndexOf("http://") != 0) 
      { 
       url = String.Format("{0}{1}", this.host, url); 
      } 

      if (method.Equals("GET")) 
       parameters = null; 

      OAuthRequest request = OAuthRequest.from_consumer_and_token(this.consumer, this.token, method, url, parameters); 
      request.sign_request(this.signature, this.consumer, this.token); 
      this.base_string = request.base_string; 

      if (method.Equals("GET")) 
       return this.http(request.to_url(), "GET", request.to_header(), null); 
      else 
       return this.http(request.get_normalized_http_url(), method, request.to_header(), request.to_postdata()); 
     } 

     private string http(string url, string method, WebHeaderCollection headers, string data = null) 
     { 
      List<string> new_http_info = new List<string>(); 
      ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); 
      HttpWebRequest request = null; 
      if (!method.Equals("DELETE")) 
       request = (HttpWebRequest)WebRequest.Create(url); 
      else 
      { 
       if (!String.IsNullOrEmpty(data)) 
       { 
        url = String.Format("{0}?{1}", url, data); 
       } 
       request = (HttpWebRequest)WebRequest.Create(url); 
      } 

      /* WebRequest settings */ 
      ((HttpWebRequest)request).ProtocolVersion = System.Net.HttpVersion.Version10; 
      ((HttpWebRequest)request).UserAgent = this.useragent; 
      ((HttpWebRequest)request).ContinueTimeout = this.connect_timeout; 
      ((HttpWebRequest)request).Timeout = this.timeout; 
      ((HttpWebRequest)request).Headers = headers; 
      ((HttpWebRequest)request).UseDefaultCredentials = true; 
      ((HttpWebRequest)request).PreAuthenticate = true; 
      ((HttpWebRequest)request).Credentials = CredentialCache.DefaultCredentials; 

      this.headers_string = headers.ToString(); 
      this.post_string = data; 

      byte[] dataByteArray = null; 

      if ((!String.IsNullOrEmpty(data) && method.Equals("POST")) || method.Equals("PUT")) 
      { 
       ((HttpWebRequest)request).ContentType = "application/x-www-form-urlencoded"; 
       System.Text.Encoding encoding = System.Text.Encoding.UTF8; 
       dataByteArray = encoding.GetBytes(data); 
       ((HttpWebRequest)request).ContentLength = dataByteArray.Length; 
       ((HttpWebRequest)request).Expect = ""; 
      } 

      switch (method) 
      { 
       case "POST": 
        ((HttpWebRequest)request).Method = "POST"; 
        if (!String.IsNullOrEmpty(data)) 
        { 
         Stream dataPost = request.GetRequestStream(); 
         dataPost.Write(dataByteArray, 0, dataByteArray.Length); 
         dataPost.Close(); 
        } 
        break; 
       case "PUT": 
        ((HttpWebRequest)request).Method = "PUT"; 
        if (!String.IsNullOrEmpty(data)) 
        { 
         Stream dataPost = request.GetRequestStream(); 
         dataPost.Write(dataByteArray, 0, dataByteArray.Length); 
         dataPost.Close(); 
        } 
        break; 
       case "DELETE": 
        ((HttpWebRequest)request).Method = "DELETE"; 
        break; 
      } 

      WebResponse response = request.GetResponse(); 

      this.http_code = ((HttpWebResponse)response).StatusCode; 

      // Get the stream containing content returned by the server. 
      Stream dataStream = response.GetResponseStream(); 

      // Open the stream using a StreamReader for easy access. 
      StreamReader reader = new StreamReader(dataStream); 

      // Read the content. 
      return reader.ReadToEnd(); 

     } 
    } 
} 

Antwort

0

Wenn Sie Ihre Eingabe String-Format json ist, können Sie Inhaltstyp ändern "application/json" und versuchen Sie, sich nach dem Hinzufügen der setRequestProperty-Header anzumelden.

Verwandte Themen