Illegal unquoted character ((CTRL-CHAR, code 10)) - rest-client

Iā€™m having issue consuming REST API. Below is my rest client. It fails at the service call with error:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value; nested exception is com.fasterxml.jackson.core.JsonParseException: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value
at [Source: java.io.PushbackInputStream#62a8dd06; line: 11, column: 55]
When I use the same json string (printed in the log) in postman, it works. It fails when I fire the request from my client.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic " + base64Creds);
try {
request = mapper.constructRequest(txnRequest, params);
logger.debug(method + " Request: " + request);
ObjectMapper map = new ObjectMapper();
logger.debug(method + " Request in json format: " +
map.writeValueAsString(request));
myRequest = new HttpEntity<MyRequest>(request, headers);
response = restTemplate.exchange(url, HttpMethod.POST, myRequest, MyResponse.class);
logger.debug(method + " response: " + response);
} catch(Exception ex) {
ex.printStackTrace();
}
Any help is much appreciated.

I switched to traditional HttpURLConnection to make this work. In this way, I'm able to set the input and output format with utf-8 and it worked. I tried to do the same with rest template, but the issue was persisting. So, I'd to switch my client implementation to HttpURLConnection

Related

Error 414 When sending invoice to Amazon MWS with _UPLOAD_VAT_INVOICE_

I'm trying to send invoices to amazon mws through _UPLOAD_VAT_INVOICE_ following the java example in this guide:
Link
pdf file is a simple invoice of 85 kb
The error is status code 414 that is "Uri too long"
Debugging original amazon class MarketplaceWebServiceClient I see this:
if( request instanceof SubmitFeedRequest ) {
// For SubmitFeed, HTTP body is reserved for the Feed Content and the function parameters
// are contained within the HTTP header
SubmitFeedRequest sfr = (SubmitFeedRequest)request;
method = new HttpPost( config.getServiceURL() + "?" + getSubmitFeedUrlParameters( parameters ) );
getSubmitFeedUrlParameters method takes every parameter and add it to querystring. One of these parameters is contentMD5 from:
String contentMD5 = Base64.encodeBase64String(pdfDocument);
So there is a very large string representing pdf file passed as parameter. This causes error 414
But that class is the original one taken from MaWSJavaClientLibrary-1.1.jar
Can anybody help me please?
Thanks
For the last 2 days I was working on the same problem,
I changed like this and it works now
InputStream contentStream = new ByteArrayInputStream(pdfDocument);
String contentMD5 =computeContentMD5Header(new ByteArrayInputStream(pdfDocument));
public static String computeContentMD5Header(InputStream inputStream) {
// Consume the stream to compute the MD5 as a side effect.
DigestInputStream s;
try {
s = new DigestInputStream(inputStream,
MessageDigest.getInstance("MD5"));
// drain the buffer, as the digest is computed as a side-effect
byte[] buffer = new byte[8192];
while (s.read(buffer) > 0)
;
return new String(
org.apache.commons.codec.binary.Base64.encodeBase64(s
.getMessageDigest().digest()), "UTF-8");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

How to handle string response in swift 3 using alamofire

I am trying to hit the url whose response is:
"dbdg96t7331e150600836bc5dc026cc1649a887fc8b921b6111172db399d03566a944946e3cd13246901128413c3c9673d4e806a4v7j2yxe".
So how can I handle this string from response? Here is my code:
temp = "Resident|" + user_uid
let url = "http://api.appname.my/encodedecode.php?text=\(temp)"
Alamofire.request(url).responseJSON { (responseObject) -> Void in
print(responseObject)
}
In response I am getting this:
FAILURE: invalidURL("http://api.appname.my/encodedecode.php?text=Resident|uP6zkPihw1MPleJQ44WV1rsH1dO2")
The pipe (|) needs to be escaped in an URL
temp = ("Resident|" + user_uid).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
and Alamofire.request might expect a real URL object
let url = URL(string: "http://api.appname.my/encodedecode.php?text=\(temp)")!

Jersey: Can I add a cookie in ContainerResponseFilter?

I have a ContainerResponseFilter and I tried to set a cookie in it as follows:
#Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
String cookieName = "ExampleCookie";
String cookieValue = "SomeData";
logger.info("Setting cookie " + cookieName + " with value " + cookieValue + " into cookies " + JsonUtils.objectToJson(containerResponseContext.getCookies()));
containerResponseContext.getCookies().put(cookieName, new NewCookie(cookieName, cookieValue));
}
But this give the following error:
Caused by: java.lang.UnsupportedOperationException: null
at java.util.AbstractMap.put(AbstractMap.java:203) ~[na:1.7.0_67]
It is not possible to set the cookie here? If it is, how would I do it?
Yeah seems a bit odd that this is not allowed. Not sure why this is not allowed. I've tested both with Jersey and Resteasy. With Resteasy, all that happens is that the cookie is not set (no Exception). I'm thinking some operation sets the cookies as headers, and by the time the filter is reached, no further operation is done with the cookies.
The only work around I can think of is to simply set the header yourself
responseContext.getHeaders().add("Set-Cookie", new NewCookie("Hello", "World"));
The toString() of NewCookie will return how it should look in the header
Set-Cookie: Hello=World;Version=1

How to prevent < converted to < when using web service proxy class in JDeveloper

I am calling a BPM web service that sends HTML email. I generated a web service proxy in JDeveloper 11.1.1.7. The type of the body of the email is xsd:string which should map to java String. I understand that certain characters, for example < > &, are reserved and converted during the xml document creation during the proxy operation.
Using SOAPUI to call the service, I can pass the body as <h1>My Heading</h1> and service responds correctly, sending the email with HTML as expected. When doing the same from a POJO that calls the proxy, <h1> is converted to <h1>My heading</h1>.
I have tried passing the body as a CDATA section but this makes no difference. I have tried converting the body to bytes then back to a UTF-8 string before the call but still no difference. I have access to the BPM service code. Is there a way I can send html to the service from a proxy, that retains the special characters?
I figured this out finally. While the JDeveloper web service proxy generator is useful most of the time, in this case it was not since I needed to send xml special characters to the service. Perhaps there is a way to manipulate the proxy code to do what you want but I couldn't figure it out.
Of particular help was this AMIS blog entry. And if you ever need to handle special characters during JAXB marshalling, this entry will help you too. A great summary of the steps to use the java URLConnection class is here and that answer points to a library that would probably make life even easier.
So here is the raw wrapper code below. The particular BPM email service we wrote also writes to a log and that explains the complex types in the raw xml input. Naturally I will populate the email values from a passed in POJO object in the main sendMail wrapper method.
package com.yourdomain.sendmail.methods;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import oracle.adf.model.connection.url.URLConnectionProxy;
import oracle.adf.share.ADFContext;
public class SendMailWrapper {
public SendMailWrapper() {
super();
}
public static void main(String[] args) throws MalformedURLException, IOException {
SendMailWrapper w = new SendMailWrapper();
w.sendMail();
}
public void sendMail() throws MalformedURLException, IOException {
String xmlInput =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:sen=\"http://xmlns.oracle.com/bpmn/bpmnProcess/SendEmailProcess\" " +
"xmlns:ema=\"http://www.wft.com/BPM/SendEmail/Email\">\n" +
"<soapenv:Header/>" +
"<soapenv:Body>\n" +
"<sen:start>\n" +
"<ema:emailInput>\n" +
"<ema:emailContent>\n" +
"<ema:toAddr>your.name#yourdomain.com</ema:toAddr>\n" +
"<ema:fromAddr></ema:fromAddr>\n" +
"<ema:ccAddr></ema:ccAddr>\n" +
"<ema:bccAddr></ema:bccAddr>\n" +
"<ema:subject>SendMail HTML</ema:subject>\n" +
"<ema:body><h1>My Heading</h1><p>Text</p></ema:body>\n" +
"<ema:contentType>text/html</ema:contentType>\n" +
"</ema:emailContent>\n" +
"<ema:emailHistory>\n" +
"<ema:projectName>Soap Test</ema:projectName>\n" +
"<ema:reqID></ema:reqID>\n" +
"<ema:compositeID></ema:compositeID>\n" +
"<ema:processID></ema:processID>\n" +
"<ema:processName></ema:processName>\n" +
"<ema:activityName></ema:activityName>\n" +
"<ema:insertDate></ema:insertDate>\n" +
"<ema:insertByID></ema:insertByID>\n" +
"<ema:insertByName></ema:insertByName>\n" +
"<ema:commentType></ema:commentType>\n" +
"<ema:commentInfo></ema:commentInfo>\n" +
"</ema:emailHistory>\n" +
"</ema:emailInput>\n" +
"</sen:start>\n" +
"</soapenv:Body>\n" +
"</soapenv:Envelope>\n";
System.out.println(xmlInput);
String wsURL = getWsdlUrl();
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = "start"; //this is the method in the service
httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
//some other props available but don't need to be set...
//httpConn.setRequestProperty("Accept-Encoding", "gzip,deflate");
//httpConn.setRequestProperty("Host", "your.host.com:80");
//httpConn.setRequestProperty("Connection", "Keep-Alive");
//httpConn.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();
//check response code...
int status = httpConn.getResponseCode();
String respMessage = httpConn.getResponseMessage();
System.out.println("RESPONSE CODE: " + status + " RESPONSE MESSAGE: " + respMessage);
//check response headers...
for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
//check error stream - this helps alot when debugging...
InputStream errorStream = ((HttpURLConnection)connection).getErrorStream();
if (errorStream != null) {
System.out.println("Error Stream: " + convertStreamToString(errorStream));
}
//if there was an expected response, you need to parse it...
/* String responseString = "";
String outputString = "";
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
isr.close();
System.out.println("OUT: " + outputString); */
}
static String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
private static String getWsdlUrl() {
String result = null;
try {
URLConnectionProxy wsConnection = (URLConnectionProxy)ADFContext.getCurrent().getConnectionsContext().lookup("SendMailProxyConnection");
result = wsConnection.getURL().toExternalForm();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
Happy coding.

Having a string how to get its contents from first `/r/n/r/n` until 2 lines from string end?

I try to create simple file upload service in C++. I get all user request body as one big string. User can upload any type of data. I need to get only user file contents from request boby string.
so for example now I have next code working with my service API provider:
std::cout << "Request body: " << request->body << std::endl << "Request size: " << request->body.length() << std::endl;
and this would print as:
Request body: ------WebKitFormBoundaryAZlJcLinxYi6OCzX
Content-Disposition: form-data; name="datafile"; filename="crossdomain.xml"
Content-Type: text/xml
яā•—ā”<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-
omain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" to-ports="*" />
</cross-domain-policy>
------WebKitFormBoundaryAZlJcLinxYi6OCzX--
Request size: 411
So I need to get from request->body (which is string) all data from first /r/n/r/n until last line -2 lines. How to do such thing with string in C++?
This isn't the most elegant approach, but one option would be to do something like this:
std::string contents = /* ... get the string ... */
/* Locate the start point. */
unsigned startPoint = contents.find("\r\n\r\n");
if (startPoint == string::npos) throw runtime_error("Malformed string.");
/* Locate the end point by finding the last newline, then backing up
* to the newline before that.
*/
unsigned endPoint = contents.rfind('\n');
if (endPoint == string::npos || endPoint == 0) throw runtime_error("Malformed string.");
endPoint = contents.rfind('\n', endPoint - 1);
if (endPoint == string::npos) throw runtime_error("Malformed string.");
/* Hand back that slice of the string. */
return std::string(contents.begin() + startPoint, contents.begin() + endPoint);
You can use regular expressions for that. This page has some nice c++ examples: http://www.math.utah.edu/docs/info/libg++_19.html