How to add header for http request - http

I am new to Restlet development, trying to add headers to do a HTTP request. I tried the following code, but got "400 bad request, the header is not valid"
String url = "http://xxxxx";
Client c = new Client(Protocol.HTTP);
Request request = new Request(Method.GET, url);
HashMap attributes = new HashMap();
attributes.put = ("DeviceID", "myDeviceID");
attributes.put = ("Centent-Type", "myCT");
attributes.put = ("User-Agent", "my user agent");
attributes.put = ("ClientID", "myCid");
request.setAttributes(attributes);
Response r =c.handle(request);
I am using Restlet 2.0.
Please help. any sample code would be great help. thanks in advance.
KC

HTTP protocol has a list of allowed headers: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
ClientID and DeviceID don't seem to be allowed headers. If you want custom headers you should prefix them with "X-".

Try using
attributes.put = ("Content-Type", "myCT");
Altough there might be other problems as well (myCT content-type?). Never used ClientID and DeviceID header also... but I'm a PHP guy :)

Related

how to change dotnet core outgoing http request hostname from the default localhost

I am able to successfully send requests to a sandbox via postman, given by a provider following their specs (see images below)
Successful request (see below)
In order to do that, aside from the respective headers and parameters (see image 2) I have to add a ssl/Tls certificate (.pfx) given that the server requires a 2 way handshake so it needs SSl client certificate:
Authorization (see below).
Headers (see below)
Body (see below)
Now, I am trying to do ir programatically using dotnet core 6, but I keep running into the same problem:
And here is my code:
public static string GetAccessToken(IConfiguration _config)
{
string UserName = Environment.GetEnvironmentVariable("USER_NAME");
string Password = Environment.GetEnvironmentVariable("PASSWORD");
var client = new RestClient("https://connect2.xyz.com/auth/token");
var request = new RestRequest();
X509Certificate2 FullChainCertificate = new X509Certificate2("Path/to/Cert/cert.pfx", "test");
client.Options.ClientCertificates = new X509CertificateCollection() { FullChainCertificate };
client.Options.Proxy = new WebProxy("connect2.xyz.com");
var restrequest = new RestRequest();
restrequest.Method = Method.Get;
restrequest.AddHeader("Accept", "*/*");
restrequest.AddHeader("Cache-Control", "no-cache");
restrequest.AddHeader("Content-Type", "application/x-www-form-urlencoded");
restrequest.AddHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes($"{UserName}:{Password}")));
restrequest.AddParameter("grant_type", "client_credentials");
RestResponse response = client.Execute(restrequest);
AccessTokenPointClickCare accessToken = JsonConvert.DeserializeObject<AccessTokenPointClickCare>(response.Content);
string strToken = accessToken.access_token;
return strToken;
}
Now, as the error seems to show, it has to do with the certificates (apparently), but I don't know if something in the code is wrong, or if I'm missing something, etc...
It is worth noting that this code did run in someone else's pc with the same set-up, but of course with that person's own pfx, but for the rest, it is essentially the same, and not to mention that it does work on my postman.
Finally, as the title on this question, the only thing I can think it might also be affecting the request is the host. If I reference the postman, there is a field where I have to place the host name of the server https://connect2.xyz.com/auth/token
So made it work by changing to a new Windows 10. Researching in other Stackoverflow threads found the answer: .NET CORE 5 '''HandshakeFailure'" when making HTTPS request
So I conclude it has to do with the cyphers

Xamarin.Forms HttpClient send get request using a simple fourSquare API-KEY

I am trying to get a connection to the Places AIP of foursquare. (https://developer.foursquare.com/reference/place-search)
This needs me the send the following authorization header:
{ "Authorization" : "<API_KEY>"} and not { "Authorization" : "<SOME_SCHEMA> <API_KEY>"}
SOME_SCHEMA being "Basic", "Key" or any other type.
--header 'Authorization: API_KEY'
I tried to set is like so
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue(Constants.API_KEY);
According to MSDN documentation this should work. but all I get is an exception saying that the header type is invalid..
Spend the day trying to found a way. but nothing I tried so far works.
I did text over curl and my api-key is good and so is the request. I really just need to get the HttpClient to accept not having a schema/type for Authorization.
This works.
it will allow to have a authorization header that does not contain an auth type.
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Accept", "application/json");
request.Headers.TryAddWithoutValidation("Authorization", Constants.API_KEY);

Blazor with ODataClient - Location Header is missing

I'm creating client side Blazor app with Microsoft.OData.Client. When I create new entity like this:
var dataServiceContext = this.ClientFactory.CreateClient<Container>(new Uri("http://localhost:5000/odata"));
var newAsset = new CreateAssetDto()
{
TechnicalName = "from_client_4",
DisplayNameFormat = "format from client",
Icon = "client/icon",
InheritedFrom = Guid.NewGuid(),
IsActive = true,
Translation = new AssetTranslationDto
{
Title = "Client Asset",
Language = "en",
Description = "This is asset from client"
}
};
dataServiceContext.AddToAssets(newAsset);
await dataServiceContext.SaveChangesAsync();
I get an exception stating that response to this POST request is missing Location header. When I run fiddle to see what's going on I can see that it actually made 2 requests.
The first request is POST but doesn't include the body and recieves 204 response.
The second request is the one that actually contains the data creating new Asset and response contains Location header as it should.
I guess OData Client is complaining about Location header missing in the response for the first request (since response for second request does contain the header). But why is it even making the first request?
Any idea how to deal with this problem?
It's possible that the first request is a preflight request sent by the browser. But normally CORS preflight requests are sent using OPTIONS method, not POST. So this case is curious.
I am a contributor to the project but do not have enough reputation to add comments here to get clarifications. Could you create an issue on https://github.com/OData/odata.net ?

How to add header in Rest aussured pf RestTemplate

I have been trying to automate some API Testing using either resttemplate or Restassured library but im facing issues on post request. I cant seems to figure how to handle this. I keep getting 415 unsupported type error , I tried many ideas already and read hundreds of threads. Please if someone have a solution let me know.
This is the developer code
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_JSON)
public Response postData(#FormDataParam("file") InputStream is,
#FormDataParam("file") FormDataContentDisposition fileName,
#FormDataParam("checkInCommInfoInput") String checkInCommInfoInput,
#HeaderParam("authorization") String authString) { }
This is what I tried with resttemplate
String addURI = "https://myURI";
HttpHeaders headers = new HttpHeaders();
//headers.add("Accept","*/*");
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", " a values will be here ");
System.out.println("**************************"+headers.getContentType());
String jsonBody = "my json file will be here";
//System.out.println("\n\n" + jsonBody);
HttpEntity<String> entity = new HttpEntity<String>(jsonBody, headers);
//POST Method to Add New Employee
response = this.restTemplate.postForEntity(addURI, entity, String.class);
responseBodyPOST = response.getBody();
// Write response to file
responseBody = response.getBody().toString();
What I tried with RestAssured
RestAssured.useRelaxedHTTPSValidation();
RestAssured.baseURI ="https://myURI";
EncoderConfig encoderconfig = new EncoderConfig();
Response response = RestAssured.given()
.header("Content-Type","application/json" )
.header("Authorization", "a vvalues will be here")
.header("Accept",ContentType.JSON )
.config(RestAssured.config()
.encoderConfig(encoderconfig.appendDefaultContentCharsetToContentTypeIfUndefined(false)))
//.contentType(ContentType.JSON)
// .accept("application/json")
.log().all().body(jsonBody).post()
.then()
.assertThat()
.log().ifError()
.statusCode(200)
.extract().response();
System.out.println("-------------"+ response.getBody().asString());
API under test #Consumes(MediaType.MULTIPART_FORM_DATA) but the test sends content with .header("Content-Type","application/json" )
415 error as you have clearly mentioned unsupported type error there is a content type mismatch between what the body content that the test client sends and what the API accepts.
See this blogpost: https://blog.jayway.com/2011/09/15/multipart-form-data-file-uploading-made-simple-with-rest-assured/ on how to do send MULTIPART_FORM_DATA

Get HTTP Response from a url by using C#

Environment: ASP.Net MVC 4 using C#
I need to get image by using GET request to a URL /inbound/faxes/{id}/image
I used the code below
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("/inbound/faxes/238991717/image");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.StreamReader stream = new StreamReader(response.GetResponseStream());
but it flags "URL not valid"
I used the complete URL www.interfax.net/inbound/faxes/{id}/image
but the result is same
I want to follow this article to receive faxes
Accepting incoming fax notifications by callback
Can anyone help me to get fax...?
Try like this:
using (var client = new WebClient())
{
byte[] imageData = client.DownloadData("http://www.interfax.net/inbound/faxes/{id}/image");
}
Notice how the url is prefixed with the protocol (HTTP in this case). Also make sure you have replaced the {id} part of the url with the actual id of the image you are trying to retrieve.

Resources