BODY=null returned from REST call, status = 302 - rest

I am making a REST Api call in my Java application :
RestTemplate restTemplateGES = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
String url = "http://myurl/common/api/usercontext";
String authToken = "token_value";
headers.add( "Content-Type", "application/json" );
headers.add( "Authorization", "Bearer " + authToken );
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<Object> respObject = restTemplateGES.exchange(url,HttpMethod.POST,entity,Object.class);
The call returns with Status=302 and Body=null.
When I make exactly the same call from INSOMNIA I am getting a response back in the form of JSON.
Not sure what I am doing wrong.

Related

GetResponseAsync timeout after a few POST request

i'm making a POST request in C# like this:
var request = WebRequest.Create("http://xxx.xxx.xxx.xxx:8080/xxx/obj/data/xxx/commands/GET");
request.ContentType = "application/json";
((HttpWebRequest)request).Accept = "application/json";
request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en");
NetworkCredential myNetworkCredentials = new NetworkCredential("myUser", "MyPass");
CredentialCache myCredentialCache = new CredentialCache
{
{ link, "Basic", myNetworkCredentials }
};
request.Credentials = myCredentialCache;
request.PreAuthenticate = true;
request.Method = "POST";
await request.GetResponseAsync();
When i'm using Postman to check the response, it's all ok, it works every time i send the request.
But programmatically, after 7-8 times, the await request.GetResponseAsync(); is giving me a Exception, "The Operation has timed out".
I don't know how to check this, in postman it's all ok, but in the app it failed after a few test. What can i do?
By default, you have only 10 Connection Limit when you start the App. So you need to setup this in the Uri for your request
ServicePoint sp = ServicePointManager.FindServicePoint(uri);
sp.ConnectionLimit = 1000;
ServicePointManager.DefaultConnectionLimit = 1000;

ionic 3 header not sending Authorizaqtion 'bearer "token"' to server

Im doing a login screen that takes a username and password.
if the login was successful the server will return a token.
then im trying to call another function to get user info but the authorization header is not being passed.
im trying my server method on postman and its working fine so i believe the problem is in the headers. May someone please advise me on what should be done?
let url = urlConst.Login;
let params1 = new HttpParams();
let loader = this.loadingcontroller.create({
content: stringEngConst.signinngin
});
let attributes = {
username: this.uname.value.toLowerCase(),
password: this.password.value,
grant_type: "password"
};
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = 'username=' + this.uname.value.toLowerCase() + '&password=' + this.password.value + '&grant_type=password';
let data: Observable < any > = this.http.post(url, body, {
headers: headers
});
loader.present().then(() => {
data.subscribe(result => {
if (result.access_token != null) {
this.signintoken = result.access_token;
this.storage.set(storageConst.SIGN_IN_TOKEN, result.token_type + " " + result.access_token);
headers.append('Authorization', 'Bearer ' + this.signintoken);
let url1 = 'http://localhost:57940/API/Account/GetUserInfo/';
let info: Observable < any > = this.http.get(url1, {
headers: headers
});
info.subscribe(result => {
/*Do Something*/
});
}
Please Note that result.access_token != null is true. and i am successfully getting the token back. But it is not being passed again to the second url (info)
Looks like this SO post may solve things for you: https://stackoverflow.com/a/47805759/6599076
You may want to use:
headers = headers.append('Authorization', 'Bearer ' + this.signintoken);
You are using the same headers as for the first http request:
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
Depending on your end point for the subsequent call it might be that you need to set headers differently:
Try creating new headers with
var headers2 = new HttpHeaders();
headers.append('Content-Type', 'application/json');
Or get rid of Content-Type completely depending on what your end point expects.
Also if you are using Ionic 3 its worth to check which Http module you are using (HttpClient or the older one) as there are some differences in how these tend to handle request options.

Get user profile from TFS REST API using credentials with RestSharp

var client = new RestClient("https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=1.0");
var request = new RestRequest(Method.GET);
var authenHeader = new AuthenticationHeaderValue("Bearer",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
request.AddHeader("Authorization", authenHeader.ToString());
request.AddHeader("Accept", "application/json");
IRestResponse response = client.Execute(request);
Response :
StatusCode: NonAuthoritativeInformation,
Content-Type: text/html;
.
.
Or this request can use only personal access token to get it?
You must use OAuth with the profiles API, it doesn't support basic auth.

ionic 3 - HttpClient response shows inn clear text or how to disable httpclient cache

This is for my understanding I am asking this question.
My client is telling, they are able to see service response in cache folder if the device is rooted/jailbreak. I am using HTTPS.
import { HttpClient, HttpHeaders, HttpEventType, HttpEvent } from '#angular/common/http';
APIBASEURL = "https://........"
//MARK:- HTTP GET method
getServiceData(path: string) {
var APIFULLURL = this.APIBASEURL + path;
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
headers = headers.set("Content-Encoding", 'gzip')
headers = headers.set('Accept', 'application/json;charset=utf-8')
headers = headers.set('Authorization', this.APIHeaderKey);
headers = headers.set('Cache-control', 'no-cache');
headers = headers.set('Cache-control', 'no-store');
headers = headers.set('Expires', '0');
headers = headers.set('Pragma', 'no-cache');
//*****************Service Log ********************//
console.log("==URL ===" + APIFULLURL);
//*****************Service Log ********************//
const req = new HttpRequest('GET', APIFULLURL,{
headers: headers,
reportProgress: true,
withCredentials : true
});
return this.http.request(req).timeout(50000)
}
//MARK:- HTTP POST method
postService(path: string, isLogin: boolean, serviceBody: any) {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
headers = headers.set("Content-Encoding", 'gzip')
headers = headers.set('Accept', 'application/json')
headers = headers.set('Authorization', this.APIHeaderKey)
headers = headers.set('Cache-control', 'no-cache');
headers = headers.set('Cache-control', 'no-store');
headers = headers.set('Expires', '0');
headers = headers.set('Pragma', 'no-cache');
var APIFULLURL = this.APIBASEURL + path;
//*****************Service Log ********************//
console.log("==URL ===" + APIFULLURL);
//*****************Service Log ********************//
try {
return this.http.post(APIFULLURL, JSON.stringify(serviceBody), { headers: headers, withCredentials : true} ).timeout(50000);
} catch (error) {
console.log(error);
alert("Error" + error)
}
}
when I call api service, httpclient is saving the response in the cache. I do not manually save in the cache or local storage.
problem is first to install and access the app, later jailbreak/ rooted, go directly to cache folder and see the service response clear text.
How can I encrypt this cache value? according to my knowledge, before the process, HttpClient save in the cache.
Please guide me how to encrypt the service response in the cache.
This is the high severity issue in my app.
How can I disable 'HttpClient to keep it in the cache?

Dropbox API How to Set Content-Type in RestRequest

Trying to call Dropbox API v2.
Dim client = New RestClient("https://api.dropboxapi.com/2/")
Dim request = New RestRequest("files/search", Method.POST)
request.AddHeader("Authorization", "Bearer " & MYTOKEN)
request.AddHeader("Content-Type", "application/json")
'request.RequestFormat = DataFormat.Json
'request.JsonSerializer.ContentType = "application/json; charset=utf-8;"
'request.AddParameter("Content-Type", "application/json")
request.AddParameter("path", "")
request.AddParameter("query", "my file")
request.AddParameter("start", "0")
request.AddParameter("max_results", "1")
request.AddParameter("mode", "filename")
Dim res = client.Execute(request)
Always return
Error in call to API function "files/search": Bad HTTP "Content-Type" header: "application/x-www-form-urlencoded". Expecting one of "application/json", "application/json; charset=utf-8", "text/plain; charset=dropbox-cors-hack"
Tried the commented code lines but still the same response. Any clue?
If my guesses are right, and this is Visual Basic code using RestSharp, then I think you need something like this (apologies if it's not quite right; I don't know VB syntax):
Dim client = New RestClient("https://api.dropboxapi.com/2/")
Dim request = New RestRequest("files/search", Method.POST)
request.AddHeader("Authorization", "Bearer " & MYTOKEN)
request.RequestFormat = DataFormat.Json
request.AddBody(New With {
.path = "",
.query = "my file",
.start = 0,
.max_results = 1,
.mode = "filename"
})
Dim res = client.Execute(request)
Solved it like this. There could be better ways to do it but this works for now.
Dim client = New RestClient("https://api.dropboxapi.com/2/")
Dim request = New RestRequest("files/search", Method.POST)
request.AddHeader("Authorization", "Bearer " & MYTOKEN)
request.AddHeader("Content-Type", "application/json") '---> this line still doesn't seem to do anything
Dim json As New JObject(New JProperty("path", ""), New JProperty("query", "my file"), New JProperty("max_results", 1), New JProperty("mode", "filename"))
request.AddParameter("application/json", json, ParameterType.RequestBody)
Dim res = client.Execute(request)
Dropbox API appears to be very sensitive as for example, the object in AddParameter cannot be a json string, it must be json object. And "1" say in max_results doesn't work, it must be 1 without the quotes. A lot of trial and error but finally worked.