none
Calling REST Service with HTTP POST RRS feed

  • Question

  • I have a Java REST service that I need to call by using POST.

    I am doing the following - 

    string postData = "version=" + AppConfig.ONESiteServiceVersion + "&serviceName=" + AppConfig.ONESiteServiceName;

    string endPoint = AppConfig.ONESiteEndPointCreateToken + "?" + postData;

    // create endpoint 
    var request = (HttpWebRequest)WebRequest.Create(endPoint);
    //WebRequest request = WebRequest.Create(endPoint);
    request.Method = "POST";
    byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
    request.ContentType = "text/xml";
    request.ContentLength = postDataBytes.Length; 
    var dataStream = request.GetRequestStream(); //this is where it erring out: NotSupported Exception
    dataStream.Write(postDataBytes, 0, postDataBytes.Length);
    dataStream.Close();

    var response = (HttpWebResponse)request.GetResponse(); //this comes out null

    Could  someone please tell me what I am doing wrong or suggest me an alternative way to to this.

    Thanks!


    • Edited by Smishra22 Tuesday, September 1, 2015 2:35 PM
    Tuesday, September 1, 2015 2:34 PM

All replies

  • At a high level it looks good but some things to validate

    1. Can you verify what your string (endpoint) really looks like because I see you are getting things from config and concatenating etc. So if you could demonstrate what that really looks like (pre-encoding) . Change it if you have too but make sure its good.

    2. Can you verify that your Rest EndPoint even accepts Posts?

    3. Can you validate what ContentType it expects (make sure its not JSON or WWW) or something else

    4. Double check your request (hover over it)

    5. Make sure your base address for post doesn't end in /

    6. Make sure that your RestFul (Parameter Template) is correct. You might be trying to pass parameters to a method that doesn't accept post, or doesn't have the correct template to take those parameters.

    Suggestion -- create another end point with NO parameters and call it by passing string.empty for your data stream (in).. and see if you get something out.

    Tuesday, September 1, 2015 9:55 PM
  • Thanks for your response. Here is my endpoint - 

    https://devservices.caremark.com:450/onesite/oneSiteToken/createToken

    I hate to say that, but I still have no clue why I am having trouble doing something so simple

    Thursday, September 3, 2015 6:41 PM
  • Hi  Smishra22,

    Dose it worked?

    Here is my sample.

     try
                {
                    string strPost = "hello here is my test app" + "By doing this, we can try to cater"
                        + " to different set of clients. RESTful "
                        + "services can be accessed by all kind of clients "
                        + "and TCP IP can be access by .Net clients. As many "
                        + "of you would already aware that the TCP/IP is"
                        + " the best suited for better performance."
                        + " At the end of article, "
                        + "I will also cover how you can test your REST based service using a fiddler tool. ";
                    byte[] buffer = Encoding.UTF8.GetBytes(strPost);
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://LocalHost:7789/MySericeDemo/postMostStr/" + buffer.Length);
                                 
                    request.Method = "POST";
                    request.ContentType = "text/plain";
                    request.ContentLength = buffer.Length;
                    System.IO.Stream requestStream = request.GetRequestStream();
                    requestStream.Write(buffer, 0, buffer.Length);
                    requestStream.Close();
                    System.IO.Stream getStream = request.GetResponse().GetResponseStream();
                    byte[] resultByte = new byte[200];
                    getStream.Read(resultByte, 0, resultByte.Length);
                    Console.WriteLine(Encoding.UTF8.GetString(resultByte));
                   
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                Console.ReadLine();
            }

    Best Regards,

    Vince Li

    Thursday, September 24, 2015 12:47 AM
  • Thanks for your response Vince, but its is still not working.. I am not sure why. Following is the error I get when I do GetRequestStream -

    Length '(stream.BaseStream).Length' threw an exception of type 'System.NotSupportedException' long {System.NotSupportedException}

    Here is my code, if you could help me out, I would really appreciate that - 

    Class containing main function -        

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Xml; namespace TestONESiteTokenService { static class Constants { public const string ENDPOINT_CREATE_TOKEN = "https://devservices.caremark.com:450/onesite/oneSiteToken/createToken"; public const string ENDPOINT_VALIDATE_TOKEN = "https://devservices.caremark.com:450/onesite/oneSiteToken/validateToken"; public const string PHY_PRTL_API_KEY = "8ed35ae6-469c-4798-b47e-910eca4ae55f"; public const string PHY_PRTL_SECRET = "b3762e52-4596-4c74-b21e-b895c08bf63b"; public const string SERVICE_VERSION = "2.1"; public const string CREATE_APP_NAME = "PHY_WEB"; public const string SERVICE_NAME = "oneSiteToken"; public const string METHOD_NAME_VALIDATE = "validateToken"; public const string METHOD_NAME_CREATE = "createToken"; public const string CHANNEL_NAME = "WEB"; public const string LOB = "MED_D"; public const string ID_TYPE = "PHY"; } class Program { static void Main(string[] args) { Payload payload = new Payload(); payload.version = Constants.SERVICE_VERSION; payload.serviceName = Constants.SERVICE_NAME; payload.operationName = Constants.METHOD_NAME_CREATE; payload.appName = Constants.CREATE_APP_NAME; payload.channelName = Constants.CHANNEL_NAME; payload.deviceID = "device12345"; payload.deviceType = "DESKTOP"; payload.deviceToken = "DEVICE12345"; payload.apiKey = Constants.PHY_PRTL_API_KEY; payload.lineOfBuiness = Constants.LOB; payload.srcMemberID = "User,PhysicianPortal,User.PhysicianPortal@NOVO.com"; payload.srcMemberIDType = "PHY"; payload.timeStamp = ToBase64Encode(DateTime.UtcNow.TimeOfDay.TotalMilliseconds.ToString()); payload.HMAC = GenerateHMAC(); using (XmlWriter writer = XmlWriter.Create("payload.xml")) { writer.WriteStartDocument(); writer.WriteStartElement("Payload"); writer.WriteElementString("version", payload.version); writer.WriteElementString("serviceName", payload.serviceName); writer.WriteElementString("operationName", payload.operationName); writer.WriteElementString("appName", payload.appName); writer.WriteElementString("channelName", payload.channelName); writer.WriteElementString("deviceID", payload.deviceID); writer.WriteElementString("deviceType", payload.deviceType); writer.WriteElementString("deviceToken", payload.deviceToken); writer.WriteElementString("apiKey", payload.apiKey); writer.WriteElementString("lineOfBusiness", payload.lineOfBuiness); writer.WriteElementString("srcMemberID", payload.srcMemberID); writer.WriteElementString("srcMemberIDType", payload.srcMemberIDType); writer.WriteElementString("timeStamp", payload.timeStamp); writer.WriteElementString("HMAC", payload.HMAC); writer.WriteEndElement(); writer.WriteEndDocument(); } //create request string endPoint = Constants.ENDPOINT_CREATE_TOKEN;// +"?" + postData; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint); request.Method = "POST"; request.ContentType = "application/xml"; System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(payload.GetType());

    //This is where the problem is - GetRequestStream System.IO.StreamWriter stream = new System.IO.StreamWriter(request.GetRequestStream()); xs.Serialize(stream, payload); //get response HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //read response string responseContent = null; using (System.IO.StreamReader responseStream = new System.IO.StreamReader(response.GetResponseStream())) { responseContent = responseStream.ReadToEnd(); } Console.WriteLine(endPoint); Console.WriteLine(responseContent); Console.ReadLine(); } static string GenerateHMAC() { //salt: UTC TimeNow string salt = DateTime.UtcNow.TimeOfDay.TotalMilliseconds.ToString(); //encoded salt string encodedSalt = ToBase64Encode(salt); //salted key string saltedAPIKey = Constants.PHY_PRTL_API_KEY + salt; string apiSecret = Constants.PHY_PRTL_SECRET; //encode apiSecret System.Text.UnicodeEncoding encoding = new UnicodeEncoding(); byte[] apiSecretBytes = encoding.GetBytes(apiSecret); //get HMAC with the encodedAPISecret above System.Security.Cryptography.HMACSHA256 signingKey = new System.Security.Cryptography.HMACSHA256(apiSecretBytes); //hash the saltedKey // 1. encode saltedKey, 2. Get hash the signingKey byte[] saltedAPIKeyBytes = encoding.GetBytes(saltedAPIKey); byte[] hMAC = signingKey.ComputeHash(saltedAPIKeyBytes); //Base64 Encoded HMAC string encodedHMAC = Convert.ToBase64String(hMAC); return encodedHMAC; } static string ToBase64Encode(string _value) { //get encoding UnicodeEncoding encoding = new UnicodeEncoding(); //encode it byte[] _valueEncode = encoding.GetBytes(_value); //convert it string _convertedValue = Convert.ToBase64String(_valueEncode); return _convertedValue; } } }

    Payload Class - 

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace TestONESiteTokenService
    {
        public class Payload
        {
            public string version { get; set; }
            public string serviceName { get; set; }
            public string operationName { get; set; }
            public string appName { get; set; }
            public string channelName { get; set; }
            public string deviceID { get; set; }
            public string deviceType { get; set; }
            public string deviceToken { get; set; }
            public string apiKey { get; set; }
            public string lineOfBuiness { get; set; }
            public string srcMemberID { get; set; }
            public string srcMemberIDType { get; set; }
            public string timeStamp { get; set; }
            public string HMAC { get; set; }
        }
    }
    


    Thursday, September 24, 2015 2:01 PM