WireMock - invalid content-length after modify body by ResponseTransformer - wiremock

I'm trying to modify response with wiremock in record mode.
I'm extending ResponseTransformer and replace an absolute url reference.
Wiremock returns modified response but doesn't update Content-Length header so chrome thinks there is few more bytes to download.
When i try add Content-Length header by :
...
Response.Builder.like(response).headers(updateContentLength(response.getHeaders(), modifiedBody.length()));
...
private HttpHeaders updateContentLength(HttpHeaders headers, int bodyLength) {
HttpHeaders newHttpHeaders = HttpHeaders.noHeaders();
for (HttpHeader header : headers.all()) {
if(header.key().equalsIgnoreCase("Content-Length"))
{
newHttpHeaders.plus(new HttpHeader(header.key(), bodyLength +""));
}
else
{
newHttpHeaders.plus(header);
}
}
return newHttpHeaders;
}
Some headers like Set-Cookie disappears
and "Transfer-Encoding: chunked" is added extra.
using:
wiremock-standalone-2.14.0.jar

1) The bug is reporoted here github.com/tomakehurst/wiremock/issues/907
2) My workaround is to not change actual content length by adding white characters in a place where a client ignores them e.g.
<script src="https://example123456.com/aaa"></script>
replace by:
<script src= "https://example.com/aaa"></script>

Related

I wana have my application to fetch a html web page but i keep getting -400 whatever i try monkey c / garmin connect

even this exemple i found on the site of garmin has the same problem
https://developer.garmin.com/connect-iq/core-topics/https/
import Toybox.System;
import Toybox.Communications;
import Toybox.Lang;
class JsonTransaction {
// set up the response callback function
function onReceive(responseCode as Number, data as Dictionary?) as Void {
if (responseCode == 200) {
System.println("Request Successful"); // print success
} else {
System.println("Response: " + responseCode); // print response code
}
}
function makeRequest() as Void {
var url = "https://www.garmin.com"; // set the url
var params = { // set the parameters
"definedParams" => "123456789abcdefg"
};
var options = { // set the options
:method => Communications.HTTP_REQUEST_METHOD_GET, // set HTTP method
:headers => { // set headers
"Content-Type" => Communications.REQUEST_CONTENT_TYPE_URL_ENCODED},
// set response type
:responseType => Communications.HTTP_RESPONSE_CONTENT_TYPE_URL_ENCODED
};
var responseCallback = method(:onReceive); // set responseCallback to
// onReceive() method
// Make the Communications.makeWebRequest() call
Communications.makeWebRequest(url, params, options, method(:onReceive));
}
}
can some one please tel me what i am doing wrong
The return code -400 means "Response body data is invalid for the request type." according to the SDK specification.
You are requesting a response type of Communications.HTTP_RESPONSE_CONTENT_TYPE_URL_ENCODED but in your question you state that you are expecting HTML to be returned, which almost certainly can't be parsed as URL encoded form parameters.
The SDK does not seem to support HTML response types. Even if you omit the expected response type, the server will probably still send "application/html" and the SDK states that "If the Content-Type header from the response is not one of the known HTTP_RESPONSE_CONTENT_TYPE_* types, an error will occur", so I guess you're out of luck.
Maybe you can try to request HTTP_RESPONSE_CONTENT_TYPE_TEXT_PLAIN in order to get the server to return text instead of HTML, which you then could use somehow?

Ionic retrieve custom headers parameter from an http.get

As the title explains, I pretend to retrieve in console.log a custom header named "count" inside a map from an http.get request. The browser shows that the count value exists. How can I retrieve that value?
This is what I have tried, the problem is that this returns null.
import { Http } from "#angular/http";
constructor (public http: Http) {}
myFunction() {
return this.http.get(url)
.map((response: Response) => {
console.log(response.headers.get('count')); // returns null
});
}
response.headers only gets this
Nevermind, I fixed it adding count to the Access-Control-Expose-Headers on the website that provides the service.
# Sets the Access-Control-Expose-Headers header.
exposedHeaders: ['count']

How to set Content-Type:application/json in ui5 oData.read() ?

When I call XSet/$count, I found the response is in xml, which is hard to parse.
I tried to call
oModel.read("/XSet/$count", {
urlParameters: "$format=json",
filters: [new Filter(this._oFilterState.aTaskFilter, false)],
});
calledXSet/$count?$format=json&$filter=(status eq 'NOT_STARTED')
returned
"System query option '$format' is not compatible with the return type."
But XSet/$count?$filter=(status eq 'NOT_STARTED')&$format=json can return a json format error response.
I want to try the second way, which is change Content-Type: application/xml to Content-Type: application/json. But failed to find this in API: https://sapui5.hana.ondemand.com/#/api/sap.ui.model.odata.v2.ODataModel/methods/read
The Model.read method requests for an XML response by setting the Accept header as
Accept:application/atom+xml,application/atomsvc+xml,application/xml
However the count request is a plaintext response. You could get the count in two ways, one would be setting the Model's payload to use json and the other way would be a jQuery AJAX call.
You could initialize the model with a json parameter set to true.
var oModel = sap.ui.model.odata.v2.ODataModel("Service_URL",{
json:true
});
This would pass a header with Accept:application/json

com.dropbox.core.DbxException$BadRequest: {"error": "OAuth 2 \"Authorization\" header is not well-formed."}

I am getting following exception on uploading file to dropbox using java api.
com.dropbox.core.DbxException$BadRequest: {"error": "OAuth 2 \"Authorization\" header is not well-formed."}
at com.dropbox.core.DbxRequestUtil.unexpectedStatus(DbxRequestUtil.java:207)
at com.dropbox.core.DbxClient$SingleUploader$1.handle(DbxClient.java:765)
at com.dropbox.core.DbxClient$SingleUploader$1.handle(DbxClient.java:761)
at com.dropbox.core.DbxRequestUtil.finishResponse(DbxRequestUtil.java:279)
at com.dropbox.core.DbxClient$SingleUploader.finish(DbxClient.java:761)
at com.dropbox.core.DbxClient.finishUploadFile(DbxClient.java:629)
at com.dropbox.core.DbxClient.uploadFile(DbxClient.java:562)
at com.dropbox.core.DbxClient.uploadFile(DbxClient.java:514)
following is my code
public DbxClient authDropbox(String authAccessToken)throws IOException, DbxException {
DbxRequestConfig dbxRequestConfig = new DbxRequestConfig("JavaDropboxTutorial/1.0", Locale.getDefault().toString());
dbxClient = new DbxClient(dbxRequestConfig, authAccessToken);
return dbxClient;
}
public String uploadToDropbox(String filePath,String fileName,String folderName,DbxClient dbxClient) throws DbxException,IOException {
String sharedUrl;
File inputFile = new File(filePath);
FileInputStream fis = new FileInputStream(inputFile);
try {
dbxClient.uploadFile("/"+folderName+"/"+ fileName,DbxWriteMode.add(), inputFile.length(), fis);
sharedUrl = dbxClient.createShareableUrl("/"+folderName +"/"+fileName);
} finally {
fis.close();
}
return sharedUrl;
}
file upload code
The error 'OAuth 2 "Authorization" header is not well-formed.' indicates that the header that contains the OAuth 2 access token doesn't match the pattern expected for the header.
The header is built for you by the SDK using the accessToken parameter you supply to the DbxClient constructor, which in your case is your authAccessToken variable.
That likely means that the value of your authAccessToken isn't a valid access token, and whatever string it does contain is causing the header to not match the pattern. For example, it might contain whitespace, which could cause this.
To fix this, you should inspect the value of your authAccessToken and see what's in it and why it's malformed, and prevent that from happening again in the future.

GWT: Response not coming back to Form onSubmitCompleteEvent when a servlet sends a file in response to browser

Code on client side :
#UiHandler("form")
void onFormSubmission(SubmitCompleteEvent event) {
hideProcessingPopUp();
if (event.getResults().contains("Exception")) {
// handle exception
}
}
Servlet code in doPost method:
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment;filename="
+ exportType + ".csv");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
response.getOutputStream(), "UTF-8"));
// Adding content
List<CustomObject> list = (List<CustomObject>) anonymousList;
for (CustomObject eachObject : list) {
writer.append(eachObject.getContent());
writer.newLine();
}
writer.flush();
// Gently close streams/writers.
close(writer);
return fileContent;
Servlet code is fine, as am getting expected data and file. Problem is with response not reaching the client side i.e., SubmitCompleteEvent. Please help me out, thanks in advance.
This is how browsers work; and the javadoc for FormPanel actually warns you about it:
The back-end server is expected to respond with a content-type of 'text/html', meaning that the text returned will be treated as HTML. If any other content-type is specified by the server, then the result HTML sent in the onFormSubmit event will be unpredictable across browsers, and the onSubmitComplete event may not fire at all.