Apache common httpclient and httppost, how to make it block? - http

I am using httpclient in org.apache.httpcomponents (version 4.5.2) for http post calls, the code I wrote:
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
post.addHeader("content-type", "application/json");
StringEntity params = new StringEntity("param");
post.setEntity(params);
HttpResponse response = client.execute(post);
/***Other code section**/
cusmtomOtherFunction();
The problem is, I want to wait until the http post call has finished, then execute cusmtomOtherFunction(), how can I make this happen?

Related

Pass FromHeader the httpClient to webapi 6.0

Below is the code, I have used to call the api. However, May I know how to pass http header
for example
Get customer has a header [FromHeader] field.
string uri = "https://localhost:7290/customers";
var response = await _httpClient.GetAsync(uri);
HttpClient GetAsync() is a shortcut for generating an instance of a HttpRequestMessage set to perform a GET for the specified URI and passing it to the SendAsync() method.
You can create your own request message instance and append additional details such as headers, then use the SendAsync() method yourself.
var request = new HttpRequestMessage(HttpMethod.Get, uri);
request.Headers.Add("header", "value");
var response = await client.SendAsync(request);
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httprequestmessage?view=net-6.0

Blazor Client HttpClient. No Content Returned

There must be something wrong with my c# code. I am trying to download some Json from an Azure Blob. I can download the Json in Postman and from MS Edge however, using my code there are no apparent errors in the request but there is no content in the response. Presumably there is something wrong with my code.
async Task GetJson()
{
var request = new HttpRequestMessage
{
Method = new HttpMethod("GET"),
RequestUri = new Uri("https://xxx.blob.core.windows.net/trading/m5.json")
};
request.Headers.Add("Accept", "application/json");
request.SetBrowserRequestMode(BrowserRequestMode.NoCors);
var response = await http.SendAsync(request);
var json = await response.Content.ReadAsStringAsync();
}
This was asked on GitHub and apparently it is by design.
When you remove request.SetBrowserRequestMode(BrowserRequestMode.NoCors); line you will see the No 'Access-Control-Allow-Origin' header is present error.
Specifiying BrowserRequestMode.NoCors does not let you bypass the Browser security rules. It just simplifies the request headers.

/authorize call keeps returning 200 not 302

I am trying to implement the authentication work flow manually by calling /authorize and get back 302 with redirect_uri which will have the authorization code as query string in the Location http response header.
when I do this using an OpenIdConnect library I get 302 response with the code in the redirect url in the Location header.
When I make the call manually using the following code
var handler = new HttpClientHandler()
{
AllowAutoRedirect = true
};
using (HttpClient client = new HttpClient(handler))
{
string url2 =
"https://sample.oktapreview.com/oauth2/auspx13uvj6eHSM9c0h7/v1/authorize?
"response_type=code&"+"client_id=0oarcfbl1dwEszi1343343&"+
"state=Uy1Sa1pNcXFsMVlscV9qQVFkTjdyRzJTaW1mSnpxxxxxxxxxxL&"+
"redirect_uri=http%3A%2F%2Flocalhost%3A4200%2Fhome&"+
"scope=openid%20groups%20profile%20email&"+
"code_challenge=xDz_AAOV0Cggf560t4kqEdDXQW3slDFKy34Pp6XTYJQ&"+
"code_challenge_method=S256&"+
"nonce=Uy1Sa1pNcXFsMVlscV9qQVFkTjdyRzJTaW1mSnxxxxxxxx";
HttpRequestMessage message2 = new HttpRequestMessage(HttpMethod.Get, url2);
var response2 = client.SendAsync(message2);
response2.Wait();
var res = response2.Result;
}
I keep getting 200 response and Location in the header is null.
How can I make this call return 302? Is this something to do with the identity provider or the way I am handling the code?
I want to do this in dotnet core

How to make a HTTP get call with request header in ASP.NET MVC to an API with Oauth2 authorization?

I'm having a hard time executing a http get call with headers to an api with oauth2 authorization.
I already tried the code below but then I'm receiving an Unauthorized response from the api. I think the problem is that because I've executed the GETASYNC() without the adding some headers. Can you help me to find a way on how to add headers before I execute the GETASYNC().
public HttpClient webApiClient = new HttpClient();
public async System.Threading.Tasks.Task<ActionResult> Index()
{
var uri = new Uri("https://myURL.com/"+ transno);
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var response = await webApiClient.GetAsync(uri);
response.Headers.Add("Accept", "application/json");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.Headers.Add("client-id", "clientid");
response.Headers.Add("client-secret", "clientsecret");
response.Headers.Add("partner-id", "partnerid");
var result = JObject.Parse(await response.Content.ReadAsStringAsync());
}

MarkLogic spring RestTemplate

Hi I am trying to get the list of graphs in MarkLogic using RestTemplate.
Below is the sample code. From the browser I can able to get the graph list, but through the Java REST Client I am getting error 401.
HttpHeaders header = new HttpHeaders();
String plainCreds = "restadmin:restpassword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encode(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
header.setAccessControlAllowCredentials(true);
header.add("Authorization", "Basic " + base64Creds);
header.setAccept(Arrays.asList(MediaType.TEXT_XML));
header.setContentType(MediaType.TEXT_XML);
HttpEntity<String> entity = new HttpEntity<String>(header);
String url = "http://localhost:8003/v1/graphs";
ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
System.out.println("Response : "+response.getStatusCode());
Please help me in resolving the issue
Try copying the HTTP auth code at https://github.com/rjrudin/ml-app-deployer/blob/master/src/main/java/com/rjrudin/marklogic/rest/util/RestTemplateUtil.java#L18 - I know it will handle HTTP basic auth against the management API on port 8002, and it should work fine on your REST API server on port 8003.

Resources