C# code to passing json data with WebService - c#

response = requests.patch( "https://<manageraddress>/api/admin/configuration/v1/conference/1/", auth=('<user1>', '<password1>'), verify=False, data=json.dumps({'pin': '1234'}) https://tsmgr.tsecurevideo.com/api/admin/configuration/v1/conference/1/"
I have tried
HttpWebRequest httpWReq =(HttpWebRequest)WebRequest.Create(string.Format("https://tsmgr.tsecurevideo.com/api/admin/configuration/v1/conference/2/"));
Encoding encoding = new UTF8Encoding();
string postData = "{\"pin\":\"1234\"}";
byte[] data = encoding.GetBytes(postData);
httpWReq.ProtocolVersion = HttpVersion.Version11;
httpWReq.Method = "POST";
httpWReq.ContentType = "application/json";//charset=UTF-8";
string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("admin" + ":" + "password"));
httpWReq.Headers.Add("Authorization", "Basic " + credentials);
httpWReq.ContentLength = data.Length;
Stream stream = httpWReq.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string s = response.ToString();
StreamReader reader = new StreamReader(response.GetResponseStream());
I am getting the error
The remote server returned an error: (501) Not Implemented.

try to send credentials in this way
string auth = string.Format("{0}:{1}", "admin","password");
string data = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
string credentials= string.Format("{0} {1}", "Basic", data );
httpWReq.Headers[HttpRequestHeader.Authorization] = credentials;
refer here for documentation in Encoding.ASCII

From the HTTP spec:
501 Not Implemented
The server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.
Sounds like the server doesn't support the PATCH method.

Related

Rest API returns 401 unauthorized exception when trying to POST to it

Here is the method. I have been working on this for quite a while, and modifying the header values and such. It still comes up with 401 Unauthorized Exception unless I include content-length header and then it will come up with another error saying the content-length header is invalid. Does anyone have any idea how to resolve this?
I have also tried doing this through an HTTPWebRequest.
Webclient Code:
public void postResponse(string supplierid, string token, string geturl, string lineid)
{
lineid = lineid.Trim();
//string postdata = ("{'supplier_id':'"+supplierid+"', 'token':'"+token+"','ci_lineitem_ids':["+lineid+"]}");
try
{
string postdata = ("{'supplier_id':'"+supplierid+"','token':'"+token+"','ci_lineitem_ids':["+lineid+"]}");
Console.WriteLine(postdata);
WebClient postWithParamsClient = new WebClient();
postWithParamsClient.UploadStringCompleted +=
new UploadStringCompletedEventHandler(postWithParamsClient_UploadStringCompleted);
postWithParamsClient.UseDefaultCredentials = true;
postWithParamsClient.Credentials = new NetworkCredential(supplierid, token);
postWithParamsClient.Headers.Add("Content-Type", "application/json");
string headerlength = postdata.Length.ToString();
//postWithParamsClient.Headers["Content-Length"] = headerlength;
postWithParamsClient.UploadStringAsync(new Uri(geturl),
"POST",
postdata);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
HTTPWebRequest
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] postBytes = encoding.GetBytes(postdata);
// used to build entire input
StringBuilder sb = new StringBuilder();
// used on each read operation
byte[] buf = new byte[8192];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(geturl);
request.Credentials = new NetworkCredential(supplierid, token);
request.Method = "POST";
request.ContentLength = postBytes.Length;
request.ContentType = "application/json";
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
You should try to use fiddler to see what you send and compare to what you server need. Check authorization header and the validity of your credentials. I think it's the first thing to do

reading a returned error object in a JSON response from external API

I am using a .net webservice to communicate via JSON with an external API (Urban Airship). There is something incorrect in my outbound JSON, and supposedly, along with the 400 Bad Request error I am seeing, they are returning a JSON object to me that has error logging that will help me identify the problem.
Only thing is, I can't figure out how to accept and read the JSON error message... all I get is the 400 Bad Request. Is there a way I can modify my code to see this returned object?
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.ContentType = contentType;
req.Method = method;
req.ContentLength = jsonDataBytes.Length;
CredentialCache credentialCache = new CredentialCache();
string username = "x";
string password = y
credentialCache.Add(uri, "Basic", new NetworkCredential(username, password));
req.Credentials = credentialCache;
req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(username + ":" + password)));
req.Accept = "application/vnd.urbanairship+json; version=3;";
dynamic stream = req.GetRequestStream();
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length);
stream.Close();
dynamic response = req.GetResponse().GetResponseStream();
StreamReader reader = new StreamReader(response);
dynamic res = reader.ReadToEnd();
reader.Close();
response.Close();

How to create HTTP post request

Hello I'm new at programing so my question might be a little bit odd. My boss ask me to create a HTTP post request using a key and a message to access our client.
I already seen the article Handle HTTP request in C# Console application but it doesn't include where I put the key and message so the client API knows its me. Appreciate the help in advance.
I believe you wanted this:
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create("http://domain.com/page.aspx");
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=user";
postData += "&password=pass";
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data,0,data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
You could use a WebClient:
using (var client = new WebClient())
{
// Append some custom header
client.Headers[HttpRequestHeader.Authorization] = "Bearer some_key";
string message = "some message to send";
byte[] data = Encoding.UTF8.GetBytes(message);
byte[] result = client.UploadData(data);
}
Of course depending on how the API expects the data to be sent and which headers it requires you will have to adapt this code to match the requirements.

Use Java to read from a REST service

I am trying to figure out how to read from a REST source that requires authentication and having no luck. I have this working fine using C# as follows:
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(filename);
request.Accept = "application/xml";
request.ContentType = "application/xml";
request.KeepAlive = true;
// this part is not used until after a request is refused, but we add it anyways
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri(filename), "Basic", new NetworkCredential(username, password));
request.Credentials = myCache;
// this is how we put the uname/pw in the first request
string cre = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(cre);
string base64 = Convert.ToBase64String(bytes);
request.Headers.Add("Authorization", "Basic " + base64);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
return response.GetResponseStream();
But for Java the following is not working:
URL url = new URL(dsInfo.getFilename());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");
conn.setRequestProperty("Content-Type", "application/xml");
BASE64Encoder encoder = new BASE64Encoder();
String encodedCredential = encoder.encode( (dsInfo.getUsername() + ":" + dsInfo.getPassword()).getBytes() );
conn.setRequestProperty("Authorization", "BASIC " + encodedCredential);
conn.connect();
InputStream responseBodyStream = conn.getInputStream();
The stream is returning:
Error downloading template
Packet: test_packet
Template: NorthwindXml
Error reading authentication header.
What am I getting wrong?
thanks - dave
In your encoding of username/password:
Java uses UTF-8 encoding, and getBytes() returns the bytes corresponding to the local host encoding (who may be or not ASCII). The javadoc of String gives you more detail.
Print the values of such encoded Strings both in c# and Java and check if they match.
The answer came from Codo in a comment - Basic instead of BASIC.

HTTP 401 Error while posting XML to REST

I am trying to post a XML to REST Service. Here's the code I am using:
I am getting following error, while calling the service.
The remote server returned an error: (401) Unauthorized.
I have also tried setting NetworkCredentials directly i.e.
NetworkCredential nc = new NetworkCredential(username, password);
serviceRequest.Credentials = nc;
Thanks for your help.
Uri address = new Uri("https://localhost:30000/restservice/");
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/json";
string data = #"<Sample XML Here>";
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(address, "Basic", new NetworkCredential(username, password));
request.Credentials = mycache;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Response.Write(reader.ReadToEnd());
}
Use Fiddler and look in the WWW-Authenticate header that is returned from the server. That will tell you what kind of authentication scheme the server supports.
Couple of things to try:
Change the content type as you're not posting json to it
Not encode the data as its expecting xml, not a binary stream
Hope this helps.
try set Credentials in request like this
request.Credentials = new NetworkCredential(username, password);

Categories