GetResponseAsync timeout after a few POST request - rest

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;

Related

Getting 403 forbidden error while accessing linkedIn 2.0 API from SharePoint 2013 web part

API: https://api.linkedin.com/v2/me?projection=(id,firstName,lastName)
App Permission: r_basicprofile, r_emailaddress, w_share
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string requesturl = "https://api.linkedin.com/v2/me?projection=(id,firstName,lastName)";
HttpWebRequest webRequest = System.Net.WebRequest.Create(requesturl) as HttpWebRequest;
webRequest.Method = "GET";
webRequest.Host = "api.linkedin.com";
//webRequest.ContentType = "application/x-www-form-urlencoded";
//webRequest.Connection = "Keep-Alive";
webRequest.Headers.Add("Authorization", "Bearer " + accessToken);
//Stream dataStream = webRequest.GetRequestStream();
//String postData = String.Empty;
//byte[] postArray = Encoding.ASCII.GetBytes(postData);
//dataStream.Write(postArray, 0, postArray.Length);
//dataStream.Close();
WebResponse response = webRequest.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(dataStream);
String returnVal = responseReader.ReadToEnd().ToString();
If you are using V2 API and you did not taken permission to use r_basicprofile then either apply for permission to use r_basicprofile to linkedin
OR use r_liteprofile + r_emailaddress for V2
(also check r_liteprofile permission is there in your app or not )
r_liteprofile for firstName,lastName,profilePicture,id
r_emailaddress for getting emailAddress
Check this : https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/migration-faq?context=linkedin/consumer/context

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.

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?

PayPal API - (401) Unauthorized when requesting Access Token

I am trying to incorporate PayPal payments into our project, but I am failing at the moment hehe.
Basically, first step is to get the access token request and response, which I am trying to do with WebRequest, but it spits out 401 at me.
Following instructions from: https://developer.paypal.com/docs/integration/direct/make-your-first-call/
Here's the code:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
WebRequest request = WebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.Credentials = new NetworkCredential("client_id", "secret");
request.PreAuthenticate = true;
string body = "grant_type=client_credentials";
byte[] buffer = Encoding.UTF8.GetBytes(body);
request.ContentLength = buffer.LongLength;
var reqStr = request.GetRequestStream();
reqStr.Write(buffer, 0, buffer.Length);
reqStr.Close();
WebResponse response = request.GetResponse();
Ofcourse, client_id and secret are replaced with real values in the code :)
Thank you for your help!
Figured it out thanks to: C# HttpWebRequest using Basic authentication
Turns out I was not using Basic Auth as intended by PayPal.
Oops :D
Hope someone finds this useful.

HTTPCLIENT: Authentication for https protocol on an asp page

I need to access an asp page running on 'https' protocol.
I am facing problems at authentication part itself. The response object returns "HTTP/1.1 200 OK" but i am getting redirected to Login page itself.
Following is my code:
public FileDownloadHttpWrapper(String url,String username, String password)
{
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
// prepare parameters
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUseExpectContinue(params, true);
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params,supportedSchemes);
mClient = new DefaultHttpClient(ccm,params);
mClient.getCredentialsProvider().setCredentials(
new AuthScope(null,AuthScope.ANY_PORT),
new UsernamePasswordCredentials(username, password)
);
}
private Object getRequest(String url)
{
HttpGet get = new HttpGet("/EvalMuniMKT/mainmenu.asp");
HttpHost target = new HttpHost(url, 443, "https");
try
{
// execute the GET
HttpResponse resp = mClient.execute(target,get);
HttpEntity entity = resp.getEntity();
System.out.println(resp.getStatusLine());
System.out.println(EntityUtils.toString(entity));
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
// release any connection resources used by the method
}
return null;
}
I think the asp site uses form based login (session), not http basic authentication. For that you may need to do login form post and hold cookie in context and pass the context while executing the actual request.
something like :
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
hc.execute(httpget, localContext);