How to set url encoded form entity and add params to form entity in rest assured? - rest

The below sample code is in http client , But I want to write the same in Rest Assured. I know we can use the http lib in rest assured as well, But I want to have in Rest assured
HttpPost pst = new HttpPost(baseUrl, "j_spring_security_check"))
pst.setHeader("Content-Type", "application/x-www-form-urlencoded")
ArrayList<NameValuePair> postParam = new ArrayList<NameValuePair>()
postParam .add(new BasicNameValuePair("j_username",username))
postParam .add(new BasicNameValuePair("j_password",password))
UrlEncodedFormEntity formEntity23 = new UrlEncodedFormEntity(postParam)
pst.setEntity(formEntity23 )
HttpResponse response = httpclient.execute(pst);

For Rest Assured you can use below code snippet.
Response response = RestAssured
.given()
.header("Content-Type", "application/x-www-form-urlencoded")
.formParam("j_username", "uName")
.formParam("j_password", "pwd")
.request()
.post(url);
As, your application is using form url-encoded content type you can set the Header type to this as mentioned above.
Hope, this helps you.

#Test
public void postRequestWithPayload_asFormData() {
given().contentType(ContentType.URLENC.withCharset("UTF-8")).formParam("foo1", "bar1").formParam("foo2", "bar2").log().all()
.post("https://postman-echo.com/post").then().log().all().statusCode(200)
.body("form.foo1", equalTo("bar1"));
}
Add content type of URLENC with charaset as UTF-8. It works will latest rest assured.

Related

Calling API from Saleforce is giving error code 500

I have a REST API to callout from Salesforce.
The authorization of the API is through access token.
I am able to get the access token through POST request in Salesforce. Also tested from Postman through that token and able to get a successful response.
I am using the below code to callout the API using the access token:
String endpoint_x = '*****';//Putting my endpoint here
Http httpObject;
HttpResponse response;
String accessToken;
accessToken = MyUtilityClass.getAccessToken();
jsonBody = json.serializePretty('', true);//Yes, My JSON is empty
HttpRequest request = new HttpRequest();
request.setEndpoint(endpoint_x);
request.setHeader('Authorization', 'Bearer '+accessToken);
request.setMethod('POST');
request.setBody(jsonBody);
httpObject = new Http();
response = httpObject.send(request);
System.debug('Response=' + response);
Getting Response value as below:
System.HttpResponse[Status=Internal Server Error, StatusCode=500]
I have tried putting '{}' in the Jsonbody. Added 'Content-Type' in header but nothing worked.
Where should I lookout for this?
In the Postman, I was not putting anything in the body, and getting a successful response.
To get the same behaviour, I was using empty string in Apex, like this:
jsonBody = json.serializePretty('', true);
But the parser was not working correctly.
To solve this, I created a class without any field:
class ClassForEmptyBody{
}
And used object of that class in the serializer:
ClassForEmptyBody classForEmptyBodyObject = new ClassForEmptyBody();
jsonBody = json.serializePretty(classForEmptyBodyObject , true);
Why are you passing json body if nothing is in there. Just skip setbody code and try.

StreamReader reads \u00fc but Postman reads OK

Probably duplicate question but I couldn't find an answer for my problem. I have this code to call a web service:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://172.21.122.1:5001/autocomplete");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
//tried this too: httpWebRequest.Accept = "gzip, deflate";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write("{ \"message\" : \"mü\" }");
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
response = "";
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
But no matter what Encoding I tried with StreamReader() c'tor, I get this response or worse: {"words":["m\u00fc\u015fteri","m\u00fc\u015fterisiyim""]}
When I use Postman or SoapUI to call the same service with the same request: {"message": "mü"},
response looks ok: {"words": ["müşteri","müşterisiyim"]}
Strange thing is: The same code works OK with many other services. It is only this specific service that the reponse is not correctly encoded. We believe there is a programming error with the service, but what I wonder is how Postman or SoapUI handles this. There should be a control in their code and if the response contains "\uxxxx", then Postman or SoapUI decodes it again.
I've checked all request / response headers in Postman and SoapUI with no luck. What can be the reason?
You have to make sure that your request is encoded correctly:
Set the Content Type to:
httpWebRequest.ContentType = "application/json;charset=UTF-8";
Check if request body is also UTF-8 encoded. Set the StreamWriter encoding to UTF-8 as well:
...
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.UTF8))
...
If you are getting the request content from other source, make sure to read it also using UTF-8 encoding.
Regex.Unescape(response) worked like a charm, thanks JosefZ!

Issue calling API gateway via Vertx client

I am trying to connect to AWS API gateway using the Vertx Webclient:
HttpRequest<Buffer> request = webClient.postAbs(targetHost);
request.putHeader("Authorization", auth);
request.putHeader("Content-Type", contentType);
request.putHeader("Host", hostName);
request.sendJson(new JsonObject(jsonData), response -> {
if (response.succeeded()) {
final JsonObject result = response.result().bodyAsJsonObject();
logger.info(result.toString());
routingContext.response()
.setStatusCode(200)
.putHeader("Content-Type", "application/json")
.end(result.toString());
} else {
logger.error(response.cause().getMessage());
routingContext.fail(new Exception(response.cause().getMessage()));
}
});
and always am receiving the same error response i.e. The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method.
But if I use a javax.ws.rs.client.WebTarget,
Client client = ClientBuilder.newClient();
WebTarget target = client.target(targetHost);
response=target.request()
.header("Authorization", auth)
.header("Content-Type", contentType)
.header("Host", hostName)
.post(jsonData,Response.class);
I am able to receive a proper response.
Any idea what Vertx web client is doing differently?
So we figured out the issue, turns out the json data that we were using was not being passed properly in the Vertx implementation.
So we can just create a new JSONObject, create the data and use this object to eveluate the aws signature as well as pass the same object in the actual API call.
Thanks!

Can any body share me java code to make a one Rest api call to IBM BPM Cloud

Can any body share a java client code which makes a Rest calls to IBM Cloud BPM. Basically I want to know how to authenticate IBM Cloud BPM.
I tried the following code but it is not working
String user_info_url="https://ustrial01.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/user/current?includeInternalMemberships=true&parts=all";
logger.info("user_info_url :" + user_info_url);
HttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(user_info_url);
String authData = "rajesh.kohir123#gmail.com" + ":" + "password";
String encoded = new sun.misc.BASE64Encoder().encode(authData .getBytes());
get.setHeader("Content-Type", "application/json");
get.setHeader("Accept", "application/json");
get.setHeader("Authorization", "Basic " + encoded);
HttpResponse cgResponse = client.execute(get);
if(cgResponse.getStatusLine().getStatusCode() != 200) {
logger.info("IBM Rest call failed");
}
if(cgResponse.getStatusLine().getStatusCode() == 200) {
logger.info("IBM Rest call Succeded");
String content = EntityUtils.toString(cgResponse.getEntity());
logger.info(content);
}
Any help is greatly appreciated
I ran your code and just made the changes in URL. It worked. I hope this helps you.
Following is the URL I used to execute an exposed service :
https://vhost031.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/service/OMS#Greetings
I used the following code to add the parameters :
String parameters = "{'name':'pramod'}";
URIBuilder builder = new URIBuilder("https://vhost031.bpm.ibmcloud.com/bpm/dev/rest/bpm/wle/v1/service/OMS#Greetings");
List nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("action", "start"));
nameValuePairs.add(new BasicNameValuePair("params", parameters));
nameValuePairs.add(new BasicNameValuePair("createTask", "false"));
nameValuePairs.add(new BasicNameValuePair("parts", "all"));
builder.setParameters(nameValuePairs);
HttpGet get = new HttpGet(builder.build());
Download the download.zip form the post.
Look at the SampleBPDProcessTests.java - Line no 103
JSONObject results = bpmClient.runBPD(BPD_ID, PROCESS_APP_ID, bpdArgs);
The actual Java Code for Rest call is available as part of "bpm-rest-client.jar"
Try this concept.
Sample Java code to start a process:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://ustrial03.bpm.ibmcloud.com:443/bpm/dev/rest/bpm/wle/v1/process?
processAppId=3u092jr02j-djaodaj.u092302c166c1&bpdId=25.jklaklaa-539a-4150-
b63e-9ef94e96e521&action=start")
.put(null)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("Accept", "application/json")
.addHeader("Connection", "keep-alive")
.addHeader("Authorization", "Basic YXJrYX24223232hQGRlbG9pdHRlLmNvbTpkZWZjb240QA==")
.addHeader("Cache-Control", "no-cache")
.addHeader("Postman-Token", "f46c1525-7a75-954c-9265-bb2b21a57f16")
.build();
Response response = client.newCall(request).execute();
A full explanation of REST integration with BPM Cloud can be found in my answer at:
How to run IBM BPM Rest api call from Post man client

Invoking REST API for making new component in JIRA

I've to make a new Component in JIRA
I found out the POST url /rest/api/2/component for making new component, but i'm unable to know what type of inputs to be given.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://localhost:8080/rest/api/2/component/");
String authorization = JiraRequestResponseUtil.conversionForAuthorization();
postRequest.setHeader("Authorization", authorization);
StringEntity input = new StringEntity("\"name\":\"Component 1\",\"description\":\"This is a TEST JIRA component\" ,\"leadUserName\":\"fred\",\"assigneeType\":\"PROJECT_LEAD\",\"isAssigneeTypeValid\":\"false\",\"project\":\"TEST\"");
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
this is the code i'm implementing.
Output i'm getting is Failed : HTTP error code : 400
Plz help.
we can't tell you. You need to find documentation on the service you are posting to.
The above code is correct, just add the { & } to the JSON string.