I am try to do POST REQUEST to api, let say the API will return a response header in thailand character 10,000 บาท. after i do the request the response i am getting the header value is 10,000 à¸à¸²à¸.
Here is the code:
RequestSpecification httpRequest = RestAssured.given().header(HeaderKey.appId,header.getAppId());
Response response = httpRequest.post(uri);
String errMessage = response.header("key-to-value-i-want");
System.out.println(errMessage);
what's missing from my code? Thanks you
Related
I want to use Java 11 HttpClient and send header first, check response and if response is OK then send the body.
How can I send header only?
this is my current code:
HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(10))
.authenticator(Authenticator.getDefault())
.build();
HttpRequest httpRequest = HttpRequest.newBuilder("someEndpoint)
.header(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.header(AUTHORIZATION, "someApiKey)
.build();
HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
However with such httpResponse I understand I send the body.
By default, the header comes first in requests.
What you asked is, The first request with header and then with a body are two different requests. A single request can't be broken this way.
If you are talking about, Http HEAD method usage, then
The HEAD method asks for a response identical to that of a GET request, but without the response body.
The HTTP HEAD method requests the headers that would be returned if the HEAD request's URL was instead requested with the HTTP GET method. For example, if a URL might produce a large download, a HEAD request could read its Content-Length header to check the file size without actually downloading the file.
an example to use HEAD method:-
var httpClient: HttpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
var requestHead = HttpRequest.newBuilder()
.method("HEAD", HttpRequest.BodyPublishers.noBody())
.uri(URI.create("https://www.test.com"))
.build();
val httpResponse = httpClient.send(requestHead, BodyHandlers.discarding());
HttpHeaders headers = response.headers();
headers.map().forEach((key, values) -> {
System.out.printf("%s: %s%n", key, values);
});
Trying to send a POST request with form-data in Body in RestAssured, however not sure how should do it.
In Postman, it's fine.
I've tried things like:
public Response create() {
return super
.given()
.contentType("multipart/form-data")
.multiPart("MetaDataOne", new File("file.txt"))
.multiPart("MetaDataTwo", new File("file2.txt"))
.basePath("/create")
.log().all()
.post()
.then()
.log().all()
.extract()
.response();
}
But seems that my files are not being sent in the request.
Console log
Multiparts
Content-Disposition form-data; name = MetadataOne; filename = file
Content-Type: application/octet-stream
{"error": 415, "description": Content type application/octet-stream not supported}
Headers
Can you try with this, This should overwrite the Content-Type as multipart/form-data rather than application/octet-stream
given().contentType("multipart/form-data").multiPart("MetaDataOne", new File("file.txt"), "multipart/form-data")
.multiPart("MetaDataTwo", new File("file2.txt"), "multipart/form-data").basePath("/create").log().all()
.post().then().log().all().extract().response();
It's very simple to consume a RESTFull webservice Api, just follow these simple steps
Step 1: Create a Request Object pointing to the Service
RestAssured.baseURI ="https://myhost.com/xyz";
RequestSpecification request = RestAssured.given();
Step 2: Create a JSON object which contains all the form fields
JSONObject jsonObject = new JSONObject();
jsonObject.put("Form_Field_1", "Input Value 1");
jsonObject.put("Form_Field_2", "Input Value 2");
jsonObject.put("Form_Field_3", "Input Value 3");
jsonObject.put("Form_Field_4", "Input Value 4");
Step 3: Add JSON object in the request body and send the Request
request.header("Content-Type", "application/json");
request.body(jsonObject.toJSONString());
Post the request and check the response
Response response = request.post("/register");
Step 4: Validate the Response
int statusCode = response.getStatusCode();
Pseudo code:
import okhttp3.*;
private final OkHttpClient mClient = new OkHttpClient.Builder().readTimeout(45, TimeUnit.SECONDS).build();
Request request = new Request.Builder().url(createUrl(path, parameters)).build();
okhttp3.Response response = mClient.newCall(request).execute();
String body = response.body().string();
System.out.print(body);
My HTTP server does not send any newlines (\n) in the BODY of the message (and I verified this using curl); when I print out the received response body from okhttp, I always see \n. Any ideas on how to let okhttp know not to add \n?
I'm trying to write a test to receive a JSON response from an API and I need to set a security token in the header for the API call. I've already verified that I am receiving a valid token from the get/token API. When I try to execute the HttpGet I am receiving a 401 status code.
Update: Does anyone have a complete list of authorization token types?
public void listAllDoctors() throws IOException {
String listAllDoctors = "/api/doctors/search";
HttpGet getDEV = new HttpGet(DEVBASE_ENDPOINT + listAllDoctors);
getDEV.setHeader(HttpHeaders.AUTHORIZATION, "token " + TOKEN);
getDEV.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
response = client.execute(getDEV);
int actualStatus = response.getStatusLine().getStatusCode();
assertEquals(actualStatus, 200);
}
I figured out that the API uses a custom header token authentication. So the line of code goes like this:
getDev.setHeader("token", "Token value goes here");
I'm sending an http get/head request using Apache HttpClient 4.x. I'm sending a request with a url like "http://example.com/getAccessToken". I'm expecting the response to be a redirect url with parameters in the returned url like "http://redirecturl.com/?code=accessTokenStuff". I want to be able to parse the response redirect url parameters, i.e. I want to get "accessTokenStuff". How can I do that?
HttpClient client = new DefaultHttpClient();
HttpHead request = new HttpHead(authUrl);
HttpResponse response = client.execute(request);
System.out.println(response.getStatusLine().getStatusCode());//returns 200
request.releaseConnection();
In a nutshell: what I want is executing an original url and then getting the result which is another url that has a parameter called "code". Then I want to get the value of that parameter.
EDIT:
I also tried this but it returns the same original URL
DefaultHttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
HttpClientParams.setRedirecting(params, false);
HttpGet request = new HttpGet(authUrl);
HttpResponse response = client.execute(request);
String location = response.getLastHeader("Location").getValue();//returns same original url
System.out.println(location);
request.releaseConnection();
Setting HttpClientParams.setRedirecting(params, true); return null
Http response do not take a form of a "redirect url". Redirect and response are both different (but related) concepts. Redirect usually means "get your response from this address instead of original one".
Having said this, you can prevent HttpClient from following a redirect, see this answer: How to prevent apache http client from following a redirect
When your HttpClient is not following the redirect, you can inspect the 'Location:' header of its response, eg:
HeaderIterator iterator = httpResponse.headerIterator("Location");
while(iterator.hasNext()) {
Header header = iterator.nextHeader();
String redirectUrl = header.getValue();
}