Gatling - print the POST request URI - post

I would like to print the URI and want to verify the POST URI request is formed correctly, Can you please advise how to verify the POST URI request if URI is substituted/formed correctly?
object BidSubmission extends HttpUtil {
val orders_feeder = csv("data/Round-1.csv").circular
def orderSubmission: ChainBuilder =
pause(pauseBy(5) seconds)
.repeat(1) {
feed(orders_feeder)
.exec(postToUri(s"${Constants.orderSubmission_URL}/#{$AuctionId}/base-orders/proxy-bid", "")
.queryParam("employeeId", "#{empNo}")
.body(StringBody(session => {
println(session)
println(session.attributes("empNo"))
val empNo = session.attributes("empNo").asInstanceOf[String]
val orderNo = session.attributes("orderNo").asInstanceOf[String]
println(s"\n\n\n $orderNo \n\n\n")
var slotNos = orderNo.replace("[", "").replace("]", "").split(" +")
println(s"\n\n\n ${generatePayload(empNo, slotNos)} \n\n\n")
generatePayload(empNo, slotNos)
" "
}))
)
}

You have to tune the logback configuration file. Please have a look at the documentation: https://gatling.io/docs/gatling/reference/current/core/configuration/#logbackxml

Related

F# making a API request to a graphql endpoint

I try to get some data from a grqphql endpoint with F#.
I use Fsharp.Data
let apiQuery = """query findData {
apiData(Model:{
PageNumber: 1,
PageSize: 100
})
{
ErrorMessage Success ValidationResult TotalCount
Data{
ItemId
}
}
}"""
let queryGraphQl () =
Http.RequestString
( apiUrl,
headers = [ ContentType HttpContentTypes.Json;
Authorization ("bearer " + token)
],
body =
TextRequest apiQuery
)
But I get (500) Internal Server Error
The same in Python works fine:
query_headers = {
"Authorization": 'bearer %s' % token,
'Content-Type': 'application/json'
}
response = requests.post(url, json={'query': apiQuery}, headers=query_headers)
Any suggestions what I am missing?
In Postman I have to add
Content-Length and Host like to be calculated when request is sent.
It appears that the F# and Python code is not equivalent. The Python code contains additional query keyword in the payload.
I don't know the specifics of your particular endpoint, but I wrote similar code using one of the public interfaces.
open System.Net
open FSharp.Data
open FSharp.Data.HttpRequestHeaders
let key = "********-****-****-****-*************"
let uri k = $"https://api.everbase.co/graphql?apikey={k}"
let gurl = uri key
let apiQuery = """{ "query" :
"{ client { ipAddress { country { name } city { name } } } }"
}"""
let connectToGraph apiUrl apiQuery =
try
let res = Http.RequestString( url = apiUrl, httpMethod="POST", body = TextRequest apiQuery, headers = [ ContentType HttpContentTypes.Json; UserAgent "mozilla" ])
res
with
| _ as ex -> ex.Message
[<EntryPoint>]
let main argv =
let res = connectToGraph gurl apiQuery
printf "Response: %A" res
0
I suppose you should separate the query in your F# code from the rest of the definition with a ':'. Also the actual payload should be wrapped in quotes/double quotes to form a valid Json value.

How to pass JSON string to another api using RESTSharp?

Problem Specification:
Resource URI : address/index.php?r=api/employee
Request Header : Content- Type: application/json
HTTP Method: POST
Request Body: { "employeeName" : "ABC","age":"20","ContactNumber": "12341234"}
The above parameters should be passed to the system as a row HTTP POST in a JSON string.
I am trying to solve this problem using RESTSharp. But I am having some problem Like after executing the request my code return a Null response and I am not sure my JSON string is passing properly or not.
Here is my Code:
public ActionResult EmployeeInfo(Employee employee)
{
//string empName = unSubscription.employeeName.ToString();
var client = new RestClient("http://localhost:21779/");
var request = new RestRequest("api/employee ", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Employee
{
employeeName = "ABC",
age = "20",
ContactNumber = "12341234"
});
request.AddHeader("Content-Type", #"application/json");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
return View();
}
Is there anything wrong with my code??
And I am little bit confused about
request.AddUrlSegment("username", "Admin") and request.AddParameter("name", "value").
Basically I want to know how to utilize AdduUrlSegment() and AddParameter().
Thanks in advance.
For using request.AddUrlSegment("username", "Admin") you should define your url template properly: var request = new RestRequest("api/employee/{username} ", Method.POST);
Also you should set Content-Type
request.AddHeader("Content-Type", #"application/json");
befor adding a Body

Set headers in a groovy post request

I need to set a header in a post request: ["Authorization": request.token]
I have tried with wslite and with groovyx.net.http.HTTPBuilder but I always get a 401-Not authorized which means that I do cannot set the header right.
I have also thought of logging my request to debug it but I am not able to do that either.
With wslite this is what I do
Map<String, String> headers = new HashMap<String, String>(["Authorization": request.token])
TreeMap responseMap
def body = [amount: request.amount]
log.info(body)
try {
Response response = getRestClient().post(path: url, headers: headers) {
json body
}
responseMap = parseResponse(response)
} catch (RESTClientException e) {
log.error("Exception !: ${e.message}")
}
Regarding the groovyx.net.http.HTTPBuilder, I am reading this example https://github.com/jgritman/httpbuilder/wiki/POST-Examples but I do not see any header setting...
Can you please give me some advice on that?
I'm surprised that specifying the headers map in the post() method itself isn't working. However, here is how I've done this kind of thing in the past.
def username = ...
def password = ...
def questionId = ...
def responseText = ...
def client = new RestClient('https://myhost:1234/api/')
client.headers['Authorization'] = "Basic ${"$username:$password".bytes.encodeBase64()}"
def response = client.post(
path: "/question/$questionId/response/",
body: [text: responseText],
contentType: MediaType.APPLICATION_JSON_VALUE
)
...
Hope this helps.
Here is the method that uses Apache HTTPBuilder and that worked for me:
String encodedTokenString = "Basic " + base64EncodedCredentials
// build HTTP POST
def post = new HttpPost(bcTokenUrlString)
post.addHeader("Content-Type", "application/x-www-form-urlencoded")
post.addHeader("Authorization", encodedTokenString)
// execute
def client = HttpClientBuilder.create().build()
def response = client.execute(post)
def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
def authResponse = new JsonSlurper().parseText(bufferedReader.getText())

Post with Robospice and okHttp

I perform a POST using Robospice and okHttp :
public String loadDataFromNetwork() throws Exception {
uriBuilder = Uri.parse(url).buildUpon();
uri = new URI(uriBuilder.build().toString());
tmp = "user=" + user + "&password=" + pwd
HttpURLConnection connect = new OkUrlFactory(client).open(uri.toURL());
// Send post request
connect.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connect.getOutputStream());
wr.writeBytes(tmp);
wr.flush();
wr.close();
// Read the response
in = connect.getInputStream();
}
Is there a better way to send a post (with Robospice/okHttp) ?
NB : my code is working fine, just want to know if it's correct or not...
The problem is that if I want to use the okHttp POST like that :
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, parameters))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
with Robospice, RequestBody and newCall and isSuccessful cannot be resolved !
Do I have a solution to use okHttp post WITH Robospice ? (I know how to make a GET, but not a POST...)

Post request by ruby code and JAva code for Rails application

i am trying to call my Rails app using Ruby code .
I m having 2 tables .
Blogposts (id,name,slug,desc)
Comments (id,data,node_id,node_type)
I m trying to post a comment through my ruby code.
The Url for me is like
http://localhost:3000/api/blogs/comment.xml?slug=blogtitle-0&comment=aaaaaaaaaaaaaaa
I dont know how to write Ruby post code for this.
The one is tried is
require 'net/http'
require 'uri'
url = URI.parse('http://localhost:3000/api/blogs/comment.xml?slug=blogtitle-0')
req = Net::HTTP::Post.new(url.path)
req.basic_auth 'aruna', 'aruna'
req.set_form_data({'comment[data]'=>'aaaaaaaaaaaaaaa'}, ';')
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
case res
when Net::HTTPSuccess, Net::HTTPRedirection
puts res.body
else
res.error!
end
end
Please help in fixing this
Edit: The same thing i am trying using Java using Jersey library file .
Here also i am not getting the result.
The one i tried in Java is,
blogBean = objBlogWrapper.postComment(slug,comment);
public BlogBean postComment(String slug, String comment) {
System.out.println(slug+""+comment);
// Create a multivalued map to store the parameters to be send in the REST call
MultivaluedMap<String, String> newBlogParam = new MultivaluedMapImpl();
// newBlogParam.add("blogpost[slug]", slug);
// newBlogParam.add("comment[data]", comment);
newBlogParam.add("slug", slug);
newBlogParam.add("comment", comment);
BlogBean blogBean = null;
try {
blogBean = webResource.path(ConfigurationUtil.POST_COMMENT).header(ConfigurationUtil.AUTHENTICATION_HEADER, authentication)
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept(MediaType.APPLICATION_XML_TYPE).post(BlogBean.class, newBlogParam);
}catch (UniformInterfaceException uie) {
if (uie.getResponse().getStatus() == 401) {
System.out.println("Can not authenticate user "+ConfigurationUtil.userName +
". Please check your username/password and try again." );
} else {
System.out.println("Error when trying to talk to app. " +
"HTTP status code "+uie.getResponse().getStatus()+"returned. Finishing.");
}
return null;
} catch (ClientHandlerException che) {
System.out.println("Error when trying to talk toapp. Network issues? " +
"Please check the following message and try again later: "+che.getMessage());
return null;
}
return blogBean;
}
where my ConfigurationUtil.POST_COMMENT="api/blogs/comment.xml";
The above doesnt show me any error nor the comment is posted ..
Please give suggestions.
Here you go,
host, phost = ['http://localhost:3000', 'http://proxyhost:2521' ]
user, password = [ 'user_name' , 'password' ]
url, p_url = [URI.parse(host), URI.parse(phost)]
resp = nil
http = Net::HTTP.new(url.host, url.port, p_url.host, p_url.port)
req = Net::HTTP::Post.new(url.path)
req.basic_auth user, password
req.set_content_type 'application/xml'
req.body = 'your_request_body'
resp = http.start{|h| h.request(req)}
You may not need a proxy host at all. But just in case if you want your request proxied through, you can use that. The resp object will have your response.
With Faraday you just do
body_resp = Faraday.post 'http://localhost:3000/api/blogs/comment.xml', {:slug => 'blogtitle-0', :comment => 'aaaaaaaaaaaaaaa'}.body
Using some external gem can help because Net::Http class in Ruby is not the most simplest API.

Resources