Displaying � instead of ü in angular2 post request - web-services

I have facing issue in displaying German Umlaut characters in HTML page of angular2 application.
My backend services are in java and it returns json String.
This is the response of the post request which is shown in network tab. and it shows ü character properly .
but if i console the data from below snippet, it shows � both in HTML ui and console .
getStackById(project: string, stackId: string, ibsessionid: string) {
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post('http://' + this.ip + ':' + this.port + '/IBPublicationBuilder/MiddlewareServlet', 'project=' + project + '&stackid=' + stackId + '&ibsessionid=' + ibsessionid + '&method=getStackById', {
withCredentials: true, headers: headers
}).map(
(res: Response) => {
console.log(res);
return res.json()}
);
}
console:
UI:

Solved the issue with the below solution.
Added
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
In the header and also Changed the server side.
As I mentioned my services were in java .
Added
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
to my my response object.

Related

What is the correct Authorization header for querying a Cosmos DB?

I am trying to query my cosmos db for documents and I am having trouble generating the correct authorization header, the example in the official documentation does not show querying.
I am trying it in Postman using Javascript by POST to this URI:
POST https://MyDatabase.documents.azure.com:443/dbs/MyContainer/colls/MyDocuments/docs
With these headers:
The authorization is generated like this:
var now = new Date().toUTCString();
pm.request.headers.upsert({key: "x-ms-date", value: now })
var verb = 'POST';
var resourceType = "docs";
var resourceLink = 'dbs/MyContainer/colls/MyCollection/docs';
var text = (verb || "").toLowerCase() + "\n" +
(resourceType || "").toLowerCase() + "\n" +
(resourceLink || "") + "\n" +
now.toLowerCase() + "\n" +
"" + "\n";
//Hash and Encode by using the masterkey.
var key = CryptoJS.enc.Base64.parse("MyMasterKey");
var signature = CryptoJS.HmacSHA256(text, key).toString(CryptoJS.enc.Base64);
var authToken = encodeURIComponent("type=master&ver=1.0&sig=" + signature);
pm.request.headers.upsert({key: "Authorization", value: authToken })
Here is the error I am getting:
{
"code": "Unauthorized",
"message": "The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'post\ndocs\ndbs/MyContainer/colls/MyCollection\nwed, 27 may 2020 19:34:41 gmt\n\n'\r\nActivityId: 724657c7-0532-4c5d-a7ff-c95900ef13cf, Microsoft.Azure.Documents.Common/2.11.0"
}
I am guessing my signature is created wrong, what is the correct format?
Our docs on our Authorization Header should have what you're looking for.
hope this is helpful.
A required fix for your scenario is that you have to remove "/docs" at the end of the resourceLink value -keep it in the request URL- and also if your containter was created using a partitionKey you have to add the following header:
'x-ms-documentdb-query-enablecrosspartition': true

Send PATCH request to Django Rest Framework

I am sending a PATCH request to my DRF server in Postman and it works perfect
However when I do the same in Python I get:
<Response [405]> http://127.0.0.1:8000/api/title/8174/
b'{"detail":"Method \\"PATCH\\" not allowed."}'
Method Not Allowed
My function that sends data:
ss_token = os.getenv('SS_TOKEN')
headers = {
'Authorization': 'Token ' + ss_token,
}
source = Source.objects.all().first()
url = source.url + str(self.ss_id) + '/'
response = requests.patch(source.url, headers=headers, data={'key':'value'})
print(response, url)
print(response.content)
print(response.reason)
return True
Do I have to send other headers to the API to make the PATCH work?
Ah looks like I made a mistake. Forgot to replace source.url with the new url variable called 'url' variable. Because that add the 'ss_id' at the url' so it becomes 'api/title/ID/' instead of just 'api/title'
url = source.url + str(self.ss_id) + '/'
response = requests.patch(url, headers=headers, data={'key':'value'})

How to access all HTTP Response Headers

I have a simple mobile app in Titanium that I'm using to debug the ability to log into our user system.
At the moment, I cannot seem to see the Set-Cookie response header as it's always returned as null.
I'm currently using Titanium SDK 1.7.5 (1.8 is horribly broken).
My code is very simple, a text book example of using the HTTPClient:
var loginReq = Titanium.Network.createHTTPClient();
var url = 'https://auth.csu.edu.au/login/login.pl';
var targetURL = 'http://my.csu.edu.au'
loginButton.addEventListener('click',function(e)
{
if (username.value != '' && password.value != '')
{
loginReq.open('POST', url);
Ti.API.info('Sending HTTP Request.');
var params = {
username: username.value,
password: password.value,
url: targetURL
}
loginReq.send(params);
}
else {
alert("Username/Password are required");
}
});
loginReq.onload = function() {
var cookie = loginReq.getResponseHeader('Set-Cookie');
Ti.API.info('Response Status: ' + loginReq.status);
Ti.API.info('Response Header - Cookie: ' + cookie);
Ti.API.info('Response Header - Location: ' + loginReq.getLocation());
if (Ti.Platform.osname !== 'android')
Ti.API.info('Headers: ' + JSON.stringify(loginReq.getResponseHeaders()));
var f = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'test.html');
f.write(this.responseText);
var webview = Ti.UI.createWebView();
webview.url = f.nativePath;
var newWindow = Ti.UI.createWindow();
newWindow.add(webview);
newWindow.open({modal:true});
};
The output is as follows:
[INFO] Sending HTTP Request.
[INFO] Response Status: 200
[INFO] Response Header - Cookie: null
[INFO] Response Header - Location: https://auth.csu.edu.au/login/login.pl?redirect=true&url=http%3a%2f%2fmy%2ecsu%2eedu%2eau
[INFO] Headers: {"Connection":"Keep-Alive","Transfer-Encoding":"Identity","Keep-Alive":"timeout=5, max=99","Content-Type":"text/html","Server":"Apache/2.2.14 (Unix) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.7d mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 Perl/v5.8.4","Date":"Thu, 02 Feb 2012 01:45:29 GMT"}
I'm just going around and around in circles as I can't seem to see what is exactly wrong here. What confuses me is that HTTPClient.getResponseHeaders() is not even documented (Titanium.Network.HTTPClient-object.html) - and doesn't work for Android.
I know there must be something there because the webview displays the authenticated page fine (you can't get there unless you're authorised + cookie).
How can I get a full list of the headers to make sure I'm getting all the headers I'm supposed to?
I've found the answer to my own question.
What I have in my code to return all headers is correct. Using HTTPClient.getResponseHeaders() is the correct method for iOS and HTTPClient.getAllResponseHeaders() for Android (no idea why there's two different ways - that could be a question for another day).
The reason I'm not seeing the cookie header is because of a bug in Titanium 1.7.5 (and still exists in 1.8.1). It's not forwarding on the cookie on a 302 redirect.
Jiras on the issues:
https://jira.appcelerator.org/browse/TIMOB-4537
https://jira.appcelerator.org/browse/TIMOB-1322

HttpWebResponse contains no cookies

I'm using HTTPWebRequest/HTTPWebResponse to interact with the site (www.lockerz.com). So, I authenticate on the site:
HttpWebRequest webRequest = (HttpWebRequest) HttpWebRequest.Create("http://www.lockerz.com/auth/login");
byte[] bytes = Encoding.ASCII.GetBytes("handle=" + textBoxEmail.Text + "&password=" + textBoxPassword.Text);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
webRequest.ContentLength = bytes.Length;
Stream os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
Then I get the response:
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
I'm watching the requests\responses using Charles and it says that in the response there must be cookies, but when I try to make a list of the cookies I get it says that there are no cookies!
foreach(Cookie c in webResponse.Cookies) {
writeToLog("Cookie Name: " + c.Name + " Value: " + c.Value);
cc.Add(c);
}
I've tried adding a CookieContainer but it doesn't work anyway.
This may apply here, I have had this problem with sessions, so I will assume the same for cookies.
You are making a call to: http://www.lockerz.com/auth/login. But if a person goes to a page without the "www." part of the url, then their cookies won't survive being sent to the "www." site, because they are different sites (as far as the cookies are concerned).
I would just make the request to "/auth/login", that way, it won't matter what the user has as the url in their browser.
Hope this works.

Using Http Post to AddList() in Sharepoint

On a remote client, I'm trying to create a new list in a sharepoint site. Right now, I'm building a CAML string and sending it via http post to my sharepoint site. I've used this method to update list items and create dws folders, but I can't seem to get AddList to work. I get an error "Remove server returned error:NotFound."
here is my CAML:
string soapEnv =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance" +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" +
" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<AddList xmlns=\"http://schemas.microsoft.com/sharepoint/soap\">" +
"<listName>" + listName + "</listName>" +
"<description>" + "A Test list" + "</description>" +
"<templateID>100</templateID>" +
"</AddList>" +
"</soap:Body>" +
"</soap:Envelope>";
return soapEnv;
I send this in an http Post with these settings:
uri = "[my sharepoint site]/_vti_bin/lists.asmx";
WebClient client = new WebClient();
client.Headers["SOAPAction"] = "http://schemas.microsoft.com/sharepoint/soap/";
client.Headers["content-type"] = "text/xml; charset=utf-8";
client.Encoding = Encoding.UTF8;
client.UploadStringCompleted += UploadStringCompleted;
try
{
client.UploadStringAsync(new Uri(uri, UriKind.Absolute), "POST", CAML);
}
catch (Exception ex)
{
MessageBox.Show("Error in upload string async: " + ex.Message);
}
Any ideas? I'm pretty certain it's not an authentication issue since I've used the exact same method in this same program to do the previously mentioned functions. The sharepoint site I'm adding the list to is a test site in which I have full read/write capabilities.
D'oh!
In this part of the soap:Envelope tag: "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance"
I had XMLSchema-instance" instead of XMLSchema\"". I needed that extra parentheses to finish that string...