post request from JSON file using selenium - api

I need to post a request from JSON file in my selenium test. The below code is showing response code as 400.
Manually tested, it's working fine and response code is 200 for the same json body.
When this json body is stored in a json file and executed the below code, then response code displays as 400.
String fileName = "D:/json/test1.json";
String json = FileUtils.readFileToString(new File(fileName), "utf-8");
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); // required url is already saved in 'url' variable.
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/JSON");
con.setRequestProperty("Accept", "application/JSON");
con.setRequestProperty("Accept-Charset", "UTF-8");
con.setDoOutput(true);
OutputStream out = con.getOutputStream();
byte[] response = json.getBytes("utf-8");
out.write(response.toString());
System.out.println(httpConn.getResponseCode());
Please, appreciate any help on this?

Related

How to corectly set the ContentType property in HttpWebRequest (or how to fix the missing Content-Type header)

I thought I'd share something that took me some time to figure out:
I wrote a simple Post method using HttpWebRequest class.
In HttpWebRequest you can't use HttpWebRequest.Headers collection to set your desired headers when there is a dedicated property for it - you must use that dedicated property. ContentType is one of them. So I created my HttpWebRequest like this:
HttpWebRequest httpWebRequest = (HttpWebRequest)webRequest;
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = false;
httpWebRequest.ServicePoint.Expect100Continue = false;
httpWebRequest.ContentType = "application/json";
somewhere below I set the body of my request like this:
using (StreamWriter streamWriter = new StreamWriter(streamWebRequest))
{
streamWriter.Write(sJson);
}
and posted the request using:
WebResponse webResponse = httpWebRequest.GetResponse();
But I kept getting a "400 - Bad Request" error, while the same request worked from Postman. After analyzing the request with Fiddler I found that when I send the request from my app, the Content-Type: application/json header is missing. All the other headers were present, except for Content-Type. I thought I'm setting it wrong, so I googled but didn't find a good answer. After much experimentation I found, that if I move the line:
httpWebRequest.ContentType = "application/json"
after this block:
using (StreamWriter streamWriter = new StreamWriter(streamWebRequest))
{
streamWriter.Write(sJson);
}
then the httpWebRequest.ContentType = "application/json" header finally appears in the request. So, for HttpWebRequest make sure you always set your HttpWebRequest's body/content first, before you set the ContentType property.
Hope it helps
My question above already has the answer, but to mark it as "Answered" I had to add this comment:
Make sure you always set your HttpWebRequest's body/content first, before you set the ContentType property.This way the "Content-Type" header will appear in the request.

The XML you provided was not well-formed or did not validate against our published schema: while calling S3 bucket from Salesforce

Folks,
A total newbie here when it comes to making end-to-end integrations. I am trying to "put" my salesforce data to the s3 bucket but receiving:
The XML you provided was not well-formed or did not validate against our published schema
Here's what I am doing:
List<Task> tasks = new List<Task>([SELECT ID from TASK WHERE Id =:recordId LIMIT 1]);
for(Task task:tasks)
{
try
{
//File Content
String Body = JSON.serialize(task);
HttpRequest req = new HttpRequest();
req.setMethod('PUT');
req.setEndpoint('callout:AWS_Credentials');
req.setHeader('Content-Type', 'application/json;charset=UTF-8');
req.setBody(Body);
Http http = new Http();
HTTPResponse res = http.send(req);
What might I be doing wrong here? Too lost to see..
Thanks in advance!
Set the content type as 'application/xml' instead of 'application/json;charset=UTF-8'
req.setHeader('Content-Type', 'application/xml');

restsharp get error (authentication)

I have a API GET call that works in postman BUT not in VS2017. I copied the code
from postman:
var client = new RestClient("http://server- d01:9000/amp/portal/api/dougtest/v1");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "19763da3-4b00-4e92-83e0-1ac75f99d219");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("X-XSRF-TOKEN", "71cf12361-8090-499a-adc3-2d5e98a04143");
request.AddParameter("undefined", "{\n \"username\":\"domain\\\\username\",\n \"password\":\"myPasswd\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
The error I am getting is unauthorized, the API required a header of X-XSRF-TOKEN with a value of 71cf12361-8090-499a-adc3-2d5e98a04143 (a fake key)
Using postman, everything works just fine, but using VS2017 I get an error:
{"status":"unauthorized","error":"Login is required","errormsg":null}
What's weird (I am new to this so pardon my ignorance)is that the header does not contain:
request.AddHeader("X-XSRF-TOKEN", "71cf12361-8090-499a-adc3-2d5e98a04143");
but rather the parameter does, which is confusing since I thought the AddHeader would add it to the header but maybe I am misunderstanding something....
any advice/suggestions would be extremely welcomed
thank you in advance
dougc
Please use the below code and check
var client = new RestClient("http://server- d01:9000/amp/portal/api/dougtest/v1");
var request = new RestRequest(Method.GET);
//Make sure to give the Valid Token
request.AddHeader("Authorization","X-XSRF-TOKEN <<Generated Token>>");
IRestResponse response = client.Execute(request);
Console.WriteLine("Response :" + response.Content);

Sending a file with XMLHttpRequest() to Tika server

I'm trying to send a PDF for content extraction to a Tika Server but always get the error: "Cannot convert text from stream using the source encoding"
This is how Tika is expecting the files:
"All services that take files use HTTP "PUT" requests. When "PUT" is used, the original file must be sent in request body without any additional encoding (do not use multipart/form-data or other containers)." Source https://wiki.apache.org/tika/TikaJAXRS#Services
What is the correct way of sendig the file with XMLHttpRequest()?
Code:
var response, error, file, blob, xhr;
file = new File("/PROJECT/web/dateien/ai/pdf.pdf");
blob = file.toBuffer().toBlob("application/pdf");
url = "http://localhost:9998/tika";
// send data
try {
xhr = new XMLHttpRequest();
xhr.open("PUT", url);
xhr.setRequestHeader("Accept", "text/plain");
xhr.send(blob);
} catch (e) {
error = e;
}
({
response: xhr.responseText,
status: xhr.statusText,
error: error,
type: xhr.responseType,
blob: blob
});
Error:
I suspect PUT request to be converted into a POST request by wakanda when there is blob in XHR body. Can you wireshark your XHR request and add details ? If so, you can probably fill an issue in wakanda (https://github.com/Wakanda/wakanda-issues/issues)
Hope it helps,
Yann

Guzzle HTTP client: Extract plain text or HTML from the response

Does anyone know how to extract html response from Guzzle HTTP client? If you look at the example below, we can get xml and json response easily but I don't know how to get plain text or HTML response string.
Documentation didn't have an option for plain text or HTML unlike json() and xml().
$client = new Client($base_url);
$request = $client->createRequest($method, $uri, null, $this->requestPayload);
$response = $client->send($request);
$xml = $response->xml(); // For XML response
$json = $response->json(); // For JSON response
$html = $response->????????(); // For plain text or HTML response
Solution:
This returns the whole response body as we see in browser.
$response->getBody(true)