HttpClient vs RestSharp: how to make the same call - httpclient

I can do the call with the RestSharp tool and i receive the right response, but can i do the same thing with HTTPClient call ? My problem is how to format the values to send in post. I try with :
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("LocIdSbme_destination", "1386" ),
new KeyValuePair<string, string>("LocIdSbme_origin", "1459"),
new KeyValuePair<string, string>("arrival_date", "20151021 16:36:00"),
new KeyValuePair<string, string>("departure_date", "20151021 19:04:00"),
new KeyValuePair<string, string>("destination", "ABBIATEGRASSO"),
new KeyValuePair<string, string>("first_class_price", ""),
new KeyValuePair<string, string>("km_distance", "92"),
new KeyValuePair<string, string>("mir_destination", "S01062"),
new KeyValuePair<string, string>("mir_origin", "S01416"),
new KeyValuePair<string, string>("origin", "ABBADIA LARIANA"),
new KeyValuePair<string, string>("second_class_price", "4.8"),
new KeyValuePair<string, string>("train_ids", "[{\"train_category\": \"REG \",\"train_id\":\"5279\"},{\"train_category\": \"REG \",\"train_id\":\"2571\"},{\"train_category\": \"S \",\"train_id\": \"24151\"},{\"train_category\": \"REG \",\"train_id\": \"10539\"}]" ),
new KeyValuePair<string, string>("user_token", "token"),
new KeyValuePair<string, string>("via_1", "1360"),
new KeyValuePair<string, string>("via_2", "1001")
};
var content = new FormUrlEncodedContent(values);
//var x = new StringContent("", Encoding.UTF8, "application/json");
var response = client.PostAsync("http://trenord.makeitapp.eu/nordcomstore", content).Result;
var responseString = response.Content.ReadAsStringAsync();
But this do not produce the same response as the RestSharp call
var client2 = new RestClient("http://cccc.xxxxx.eu/mymethod");
var request2 = new RestRequest(Method.POST);
request2.AddHeader("postman-token", "92ee3ab6-26a0-68e7-47e2-cbf888565111");
request2.AddHeader("cache-control", "no-cache");
request2.AddHeader("content-type", "application/json");
request2.AddHeader("secret", "8717fe31eb803692a1241exxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
request2.AddParameter("application/json", "{ \"LocIdSbme_destination\":\"1386\",\r\n \"LocIdSbme_origin\" : \"1459\",\r\n \"arrival_date\" : \"20151021 16:36:00\",\r\n \"departure_date\" : \"20151021 19:04:00\",\r\n \"destination\" : \"ABBIATEGRASSO\",\r\n \"first_class_price\": null,\r\n \"km_distance\":92,\r\n \"mir_destination\":\"S01062\",\r\n \"mir_origin\": \"S01416\",\r\n \"origin\":\"ABBADIA LARIANA\",\r\n \"second_class_price\":\"4.8\",\r\n \"train_ids\" :[\r\n {\r\n \"train_category\": \"REG \",\r\n \"train_id\":\"5279\"\r\n },\r\n {\r\n \"train_category\": \"REG \",\r\n \"train_id\":\"2571\"\r\n },\r\n {\r\n \"train_category\": \"S \",\r\n \"train_id\": \"24151\"\r\n },\r\n\t\t{\r\n \"train_category\": \"REG \",\r\n \"train_id\": \"10539\"\r\n }\r\n ],\r\n \"user_token\":\"token\",\r\n \"via_1\": \"1360\",\r\n \"via_2\":\"1001\"\r\n}", ParameterType.RequestBody);
IRestResponse response2 = client2.Execute(request2);
Thanks in advance to all of you

The problem is at your: request2.AddParameter("application/json"
On the first example, using HttpClient, you are using FormUrlEncoded.
Try changing the RestSharp code as your HttpClient:
request2.AddParameter("application/x-www-form-urlencoded", ...)

Related

Blazor Server App Multipart Form from iPhone Content Length is 0

I have this code in my WEB API that validates if the content received is multipart:
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
I do this from my Blazor Web App to POST the content:
private async Task LoadImage(InputFileChangeEventArgs e)
{
MultipartFormDataContent content;
var file = e.File;
var fileContent = new StreamContent(file.OpenReadStream());
fileContent.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
content = new MultipartFormDataContent();
content.Add(
content: fileContent,
name: "\"file\"",
fileName: file.Name);
var metadataContent = new StringContent(JsonConvert.SerializeObject(metadata));
content.Add(
content: metadataContent,
name: "\"metadata\""
);
using (HttpClient httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(Configuration["backendurl"] + "/api/saveimage/save", content);
}
If I post the form from my PC browser everything works. BUT if I post the same information from an iPhone the Content-Length is 0 and the IsMimeMultipartContent() returns false in my backend.

Keycloak - Add/Remove Realm role from a user using APIcalls

passing userRepresentation.id
to keycloakServerURL + "/auth/admin/realms/XXXX/users/"+userId+"/role-mappings/realm"
I get these roles for a certain user...
[
{
"id": "xxxxxxx-1faf-4604-832a-fa7ab7eb4344",
"name": "uma_authorization",
"description": "${role_uma_authorization}",
"composite": false,
"clientRole": false,
"containerId": "XXXX"
},
{
"id": "xxxxxxx-ad9f-444e-adf4-be11ab7a3d98",
"name": "member_paid",
"description": "Membership Paid",
"composite": false,
"clientRole": false,
"containerId": "XXXX"
},
{
"id": "xxxxx-2d73-48a8-844d-a953cb570270",
"name": "offline_access",
"description": "${role_offline-access}",
"composite": false,
"clientRole": false,
"containerId": "XXXX"
}
]
I cannot figure out which API I am supposed to use to add/remove a role from/to the User.
Please can you advise what is the API I need to use
The best I can find is this one below but I don't know what the params (Path and request property should be)...
public void removeRole(JsonObject userToken, String clientId, String role) throws IOException {
/auth/admin/realms/XXXX/groups/" + role + "/role-mappings/clients/" + clientId);
...
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("id", clientId);
con.setRequestProperty("name", role);
....
Endpoints are
Get Role Mappings:
GET /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm
Add Role Mappings:
POST /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm
Delete Role Mappings:
DELETE /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm
Example Add Role
You have a role e.g. named testrole with the id dc5572a5-b7e0-4c4b-b841-dc88108df70f (you see it in the url when you have opened the keycloak admin GUI, or you fetch it with some other RestAPI Request)
Now we have a Request of Type POST to the endpoint /auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm with a body of type application/json and the following body-value
[
{
"id": "dc5572a5-b7e0-4c4b-b841-dc88108df70f",
"name" : "testrole"
}
]
After successful execution you get a response with HTTP-Code 204 => The testrole - role mapping is applied to this user
Example Curl Request
curl --request POST \
--url http://localhost/auth/admin/realms/{Realm}/users/{userid}/role-mappings/realm \
--header 'authorization: Bearer eyJh......h3RLw' \
--header 'content-type: application/json' \
--data '[
{
"id": "dc5572a5-b7e0-4c4b-b841-dc88108df70f",
"name" : "testrole"
}
]'
If you want to delete it again, just send the same request (same body) but with the HTTP-method DELETE instead of POST
Please let me now if this solved your issue
Based on the post above by Evil to help me...
Using Java (and JEE 8 for the good JSON capabilities)
Get the token (using a client you set up in keycloak with access type of confidential and access to the right roles (for 9.0.0 this is even more hidden now).
public JsonObject getToken() throws IOException {
String keycloakServerURL = environmentService.getEnvironmentVariable(EnvironmentService.KEYCLOAK_SERVER);
String appClientId = environmentService.getEnvironmentVariable(EnvironmentService.APP_CLIENT_ID);
String appClientSecret = environmentService.getEnvironmentVariable(EnvironmentService.APP_CLIENT_SECRET);
URL url = new URL(keycloakServerURL + "/auth/realms/XXXXXX/protocol/openid-connect/token");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
String userpass = appClientId + ":" + appClientSecret;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
con.setRequestProperty("Authorization", basicAuth);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
/* Payload support */
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes("grant_type=client_credentials");
out.flush();
out.close();
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new
InputStreamReader(con.getInputStream()));
JsonReader jsonReader = Json.createReader(in);
JsonObject responesAsJson = jsonReader.readObject();
in.close();
con.disconnect();
// Pretty Print of String
ObjectMapper objectMapper = new ObjectMapper();
String jSonstring = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(responesAsJson);
logger.info("Response: " + jSonstring);
// Pretty Print of String
logger.info("Response status: " + status);
//String contentString = responesAsJson.toString();
//logger.info("Response: " + contentString);
return responesAsJson;
}
then add a role (similar for remove - see post above)
public void addRole(JsonObject userToken, String userId, RoleRepresentation role) throws IOException {
String keycloakServerURL = environmentService.getEnvironmentVariable(EnvironmentService.KEYCLOAK_SERVER);
URL url = new URL(keycloakServerURL + "/auth/admin/realms/XXXXXX/users/" + userId + "/role-mappings/realm");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
String accessTokenFromUserToken = userToken.getString("access_token");
con.setRequestProperty("Authorization", "Bearer " + accessTokenFromUserToken);
con.setRequestProperty("Content-Type", "application/json");
/* Payload support */
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
JsonObject theBodyPart = Json.createObjectBuilder().
add("id", role.getId()).
add("name", role.getName()).
build();
JsonArray theBodyPartAsArray = Json.createArrayBuilder().add(theBodyPart).build();
String theBodyPartAsJson = theBodyPartAsArray.toString();
out.writeBytes(theBodyPartAsJson);
out.flush();
out.close();
int status = con.getResponseCode();
logger.info("Response status: " + status);
con.disconnect();
}

Getting BLOB data from XHR request in ionic 2

Can any one tel that how to GET Blob XHR request and XMLHttpRequest in ionic 2 , i have to fetch image url from the api .
This is my Ajax Code, i want in ionic 2
xhr.open('GET', "https://getbytitle('LE_COE_Mapping')/items(2)/AttachmentFiles('3.jpg')/$value");
xhr.responseType = 'blob';
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// xhr.setRequestHeader('Authorization', 'Token token="' + token + '"');
xhr.setRequestHeader('Authorization', token);
xhr.onload = function (e) {
var img = new Image();
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
document.getElementById('Doctitle').appendChild(img);
// alert(url.createObjectURL(this.response));
};
xhr.send();
Please i am stuck in this from the last two days.
Please Help me.
Thanks
I also got stuck in same problem once then this what I did :
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//this.response is your final response
console.log(this.response, typeof this.response);
var img = // your img syntax
//your any custom code goes here
}else{
//show error message if you want to show
}
}
xhr.open('GET', 'http://Your image url');// image url be like http://ab.cd/img.png
xhr.responseType = 'blob';
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
//xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//send authorisation if you sending token
xhr.send();
Hope this will help you.
what i solved this below:
this.array: this is the url which we pass to get the blob url of the particular url:
const headers1 = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': "Bearer " + this.accessToken,
'X-Requested-With': 'XMLHttpRequest'
})
const response = await this.http.get(this.array + "/$value", { headers: headers1, responseType: 'blob' }).toPromise();
let b: any = new Blob([response], { type: 'application/octet-stream' });
var url = window.URL.createObjectURL(b);
console.log("this is url BLOB " + url);

Google Vision Rest API in Xamarin

I'm trying to call the Google Vision REST API from a Xamarin.Forms app. I have the following code:-
private async void SendToGoogle(MediaFile file)
{
using (HttpClient client = new HttpClient())
{
string uri = "https://vision.googleapis.com/v1/images:annotate?key=API_KEY";
HttpResponseMessage response;
var stream = file.GetStream();
using (var content = new StreamContent(stream))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
content.Headers.ContentLength = stream.Length;
response = await client.PostAsync(uri, content);
var resp = await response.Content.ReadAsStringAsync();
}
}
}
But this is returning me a 400 error message:
Invalid JSON payload received. Expected a value.

ionic 2 http request after oauth not working

I have a button redirect to this function
loginGoogle() {
this.cordovaOauthG.login().then((success) => {
console.log("Google Login DONE ");
if (success != null) {
console.log(JSON.stringify(success));
//alert(success.access_token);
if (success.access_token != null && success.access_token != '') {
var params = "google_id=" + success.access_token;
// var token = success.access_token;
// this.postLoginGoogle(params);
this.tesLogin();
}
}
}, (error) => {
alert(error);
});
}
and this is the function for http request
tesLogin(){
// var params = "google_id="+gid;
var params = "google_id="+'ya29.Ci_4ApeVHCD7av30Y82JRZPLG4T9ZUgmU1SNLUGIlVV_ufAcCoBc4ILqsY6Ah55i-g';
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
console.log(params);
this.http.post(Config.base_url + 'api/user-account/login-google', params, {headers: headers})
.map(res => res.json()).subscribe(data => {
console.log(data);
if (data.success) {
this.local.set('access_token', data.message);
this.menu.enable(true);
this.nav.setRoot(HomePage);
}
else {
this.doAlert("Incorrect email or password");
}
});
}
My problem is, whenever I tried to call using success.access_token, it doesnt work
but If I am calling the request without any parameters(just throwing in some random strings) then it works
I tried to debug it using mobile inspector from chrome, either way it is returning a error like this (working post & not working post both returning error)
EXCEPTION: SyntaxError: Unexpected token < in JSON at position 1
I suggest to send the authentication token in the header not in the parameters. Something like that:
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', 'Bearer ' + authToken);