Use Java to read from a REST service - c#

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.

Related

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();

C# code to passing json data with WebService

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.

using catchoom in c#

i want to use catchoom in c# , but not able to find any sample
could any one please provide any sample code if have.
i have got this sample of curl
can some one covert this to c#
curl -F "image=#CATask1-Correct.png" -F "token=sometoken" https://r.catchoom.com/v1/search
i tried to convert it like this
string url = "https://r.catchoom.com/v1/search";
WebRequest myReq = WebRequest.Create(url);
myReq.Headers["token"] = "sometoken";
myReq.Headers["image"] = "imageurl";
string username = "someid";
string password = "pwd";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
myReq.Credentials = mycache;
myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
WebResponse wr = myReq.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
But throws error, 404 not found
Thanks
You should encode the post parameters in form-multipart format, as described in the W3C page. This answer shows how to encode in form-multipart format using C#
Also, if you are using the Microsoft .NET Framework >= 4.5, you may use the HttpClient class as this answer explains.
Hope this help you ;)

Send login details with HttpWebRequest

I'm trying to get this bit of code to pause/unpause my XBMC Player
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUrl+playPause);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
Debug.WriteLine(resStream);
And I need to send my login data with it, lets say its MyUsername and SuperPassword.
How would I add that data intp the request? I tried request.Headers.Add("Authorization", "MyUsername SuperPassword"); but I still get the 401 error from it.
EDIT: Nevermind, i figured it out
String username = "MyUsername";
String password = "SuperPassword";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
There is a awesome post about Send login details with HttpWebRequest and the link is post link
if You feel brother then you can also try one my Best solve this by using webClient class. example:
var url = #"...";
var mybar= new System.Collections.Specialized.NameValueCollection();
mybar.Add("username", "username");
mybar.Add("password", "password");
var client = new System.Net.WebClient();
var data = client.UploadValues(url, mybar);
var res = System.Text.Encoding.ASCII.GetString(data);
Console.WriteLine(res);
Console.ReadLine();

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