Setting RequestHeaders for Get REST API in Visual Basic - vb.net

I have located some sample source code in visual basic to call a REST API. However, I need to modify the code by adding two request headers.
' Create the web request
request = DirectCast(WebRequest.Create(sURI), HttpWebRequest)
'Update request headers with request pairs Header1/"header1 value" and header2/"header2 value"
??? HttpWebRequest.headers.Add ????
' Get response
response = DirectCast(request.GetResponse(), HttpWebResponse)
' Get the response stream into a reader
reader = New StreamReader(response.GetResponseStream())
Any help would be appreciated. Thanks!

Many of the normal headers are "built-in," like so:
HttpWebRequest.ContentType = "application/x-www-form-urlencoded"
Alternatively, you should be able to set any header you like with:
HttpWebRequest.Headers("Header1") = "Header1 value"
And another method in line with your original code:
HttpWebRequest.Headers.Add("Header1", "Header1 value")

You could consider using System.Net.WebClient.
Here is some code in C#
using (System.Net.WebClient client = new System.Net.WebClient())
{
string userInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("user:password"));
client.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " + userInfo;
client.DownloadString(url)
}

Related

What's wrong with the API call request

Working on a third part API host. The API call requires a few key/value pairs in the request body with the following example fields:
field1: fieldValue1
field2: fieldValue2
field3: fieldValue3
field4: fieldValue4
The content type should be "application/x-www-form-urlencoded".
When using Postman to make the call, it's always successful. However, when changed to use a simple service to make the call, it's failing. The following is the piece of code that set up the HttpRequestMesage and make the call:
HttpResponseMessage response;
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://soem.thirdpartyAPIHost.net"))
{
request.Content = new StringContent("{\"field1\":\"fieldValue1\",\"field2\":\"fieldValue2\",\"field3\":\"fieldValue3\",\"field4\":\"fieldValue4\"}", Encoding.UTF8, "application/x-www-form-urlencoded");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
response = await httpClient.SendAsync(request);
}
}
What's wrong with this implementation?
Found the issue: the content type is Url encoded and therefore the string cannot be in Json format. Instead, the content key/value pairs should be chained together using '&', just like when the parameters are embedded in the Url. So, the sample content in the question should be like this:
request.Content = new StringContent("field1=fieldValue1&field2=fieldValue2&field3=fieldValue3&field4=fieldValue4", Encoding.UTF8, "application/x-www-form-urlencoded");
Please also reference the following: How to send a POST request with Content-Type "application/x-www-form-urlencoded"

What should be the java code for rest-assured api for getting the access token

I want to get access token from the given REST-API call.
I have tested this in postman and it is working fine which needs data to be entered in all 3 tabs( Authorization, Header and body and need to fire post method). Please find the attached screenshots for better clarity.
Please guide me how to automate this with java and jayaway restassured library or any other solution.
Postman screenshot- Authorization tab
Postman Screenshot - Header tab
Postman screenshot- Body tab
Note: Username and password is different in Authorization and in different in Body tab
RestAssured.baseURI = "http://URI";
Response res = given().header("Content-Type", "application/json")
.body("{" + " \"username\":\"yourmail#something.com\"," + " \"password\":\"ab#1234\""
+ "}")
.when().post("/api/token").then().log().all().assertThat().statusCode(200)
.contentType(ContentType.JSON).extract().response();
String responseString = res.asString();
System.out.println(responseString);
JsonPath js = new JsonPath(responseString);
String str = js.get("data.access_token");
System.out.println(str);
Assuming that your response will look like this:
{"token_type":"bearer","access_token":"AAAA%2FAAA%3DAAAAAAAA"}
You can try following Rest Assured example:
JsonPath jsonPath = RestAssured.given()
.auth().preemptive().basic("username", "password")
.contentType("application/x-www-form-urlencoded")
.formParam("username", "johndoe")
.formParam("password", "12345678")
.formParam("grant_type", "password")
.formParam("scope", "open_d")
.when()
.post("http://www.example.com/oauth2/token")
.then()
.statusCode(200)
.contentType("application/json")
.extract().jsonPath();
String tokenType = jsonPath.getString("token_type");
String accessToken = jsonPath.getString("access_token");

Trying to add all cookies together from a webrequest, but when I print it, it sends back system.net.cookiecontainer

I am struggling getting a cookie, from a website, when I alert the cookie,it just returns: system.net.cookiecontainer Here's how I am trying to get the cookie:
'get the cookie for the post request !important
Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://www.dailymail.co.uk/home/index.html"), HttpWebRequest)
req.Method = "GET"
'iniate the cookie container for the post request
Dim tmpcookie As New CookieContainer
'get the cookie.
Dim postcookie = DirectCast(req.GetResponse(), HttpWebResponse)
tmpcookie.Add(postcookie.Cookies)
'assign the cookie to use outsie the scope (background worker)
textcookie = tmpcookie.ToString()
but when I alert textcookie I get what I said above :(
tmpcookie is a CookieContainer. You're calling ToString on a CookieContainer, it does what it's specified to do: output the fully qualified type name, "System.Net.CookieContainer".
It's like doing (New List(Of Object)).ToString() - it's going to output "System.Collection.Generics.List", not a string representing every item in that list.
You'll want to iterate the cookies in that container, and concatenate/build (?) a string from each individual cookie in that container.

Flowgear Workflow Call using JAVA Post API

Please help how to call flowgear workflow using JAVA POST API.
My flowgear end point is 6.somesubdomain.mydomain(This end point is valid?).I used this code to call flowgear workflow but it is not work my end point is not call(please check my end point is valid).
URL myURL = new URL("https://6.somesubdomain.mydomain.flowgear.io/test/");
HttpURLConnection con = (HttpURLConnection)myURL.openConnection();
String userCredentials = "email:password";
String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.connect();
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(somejsondata.toString());
osw.flush();
osw.close();
Please give me response.
Thanks.

Box.com create/update folder from salesforce using api v2

I am trying to create a new folder in the Box from a controller class in salesforce using the api version 2. I am receiving the access token and i am also been able to retrieve the items of a folder with a HTTP GET request.
But I am not able to create a new folder in BOX. Also not able to copy files from 1 folder to another or update information about a folder.
Below is the code to update the Description of my folder:
Http h = new Http();
HttpRequest req = new HttpRequest();
string endPointValue = 'https://api.box.com/2.0/folders/myfolder_id';
req.setEndpoint(endPointValue);
req.setHeader('Authorization', 'Bearer ' + myaccessToken);
req.setBody('description=' + EncodingUtil.urlEncode('New', 'U`enter code here`TF-8'));
req.setMethod('POST');
HttpResponse res = h.send(req);
I am getting the following response:
{"type":"error","status":400,"code":"bad_request","context_info":{"errors":[{"reason":"invalid_parameter","name":"entity-body","message":"Invalid value 'description=New'. Entity body should be a correctly nested resource attribute name\/value pair"}]},"help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Bad Request","request_id":"my request Id"}
Can anyone help me on this?
Thanks in advance!
According to documentation here, Box API expects request parameters in JSON format and request method has to be PUT. Try following:
Http h = new Http();
HttpRequest req = new HttpRequest();
string endPointValue = 'https://api.box.com/2.0/folders/myfolder_id';
req.setEndpoint(endPointValue);
req.setHeader('Authorization', 'Bearer ' + myaccessToken);
req.setBody('{"description" : "New folder description"}');
req.setMethod('PUT');
HttpResponse res = h.send(req);
P.S. you were also using EncodingUtil.urlEncode() method incorrectly. First parameter should be a string you are trying to make URL-safe and second parameter is encoding (see documentation here)