I have to send some data using POST to a backend that checks the content type and forces "text/xml".
I'm using this code:
final ClientResource resource = new ClientResource(url);
String data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> ..."
StringRepresentation stringRep = new StringRepresentation(data);
stringRep.setMediaType(MediaType.TEXT_XML);
resource.post(stringRep);
It seems that Restlet uses "text/plain" as content type. Is it possible to force the content type? I'm using Restlet 2.0 on Android 2.2.
Thanks in advance
Steven
I made some tests using the code your gave with Restlet 2.0.3 and changing the content type on the representation actually changes the corresponding header in HTTP request.
You say "It seems that Restlet uses "text/plain" as content type". How do you check that? On my side, I used the Tcp Mon tool from Apache as a proxy to see the request content (http://ws.apache.org/commons/tcpmon/download.cgi). Otherwise which 2.0 version do you use? This will allow having the same environment as you...
Thanks,
Thierry
Related
I have a Java RESTlet v2.1.2 method like this:
#Post("json")
public Representation doPost(Representation entity) throws UnsupportedEncodingException {
Request request = getRequest();
String entityAsText = request.getEntityAsText();
logger.info("entityAsText = " + entityAsText + " Üüÿê");
in the Cygwin console it prints:
2015-04-19 22:07:27 INFO BaseResource:46 - entityAsText = {
"Id":"xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx",
"Field1":"John?????????",
"Field2":"Johnson??????????"
} ▄³ Û
As you can see the Üüÿê is printed as ▄³ Û. The characters Üüÿê are also in the POST body of SOAP UI. But they're printed as ???. I have an implemantation which does not use RESTlet where this works. So the settings in SOAP UI are not the problem. (The POST body is in Application/JSON btw.)
How can I extract the unicode chars Üüÿê from the POST body without getting them as ??? ?
I made a test and it works for me but perhaps I don't have same configuration regarding charset / encoding. I used a standalone Restlet application (no servlet) from Postman. Can you give us more details about the version of Restlet and the different editions / extensions you use (for example, Jackson, Servlet, ...)?
Here is what I have for Java (you can have a look at this link: How to Find the Default Charset/Encoding in Java?):
Default Charset=UTF-8
file.encoding=Latin-1
Default Charset=UTF-8
Default Charset in Use=UTF8
You can also specify the charset you sent for your content at the level of the header Content-Type: application/json;charset=utf-8.
I wrote a post some years ago about such issues when using a servlet container. Perhaps could you also find out some hints to help you: https://templth.wordpress.com/2011/06/05/does-your-java-based-web-applications-really-support-utf8/.
Hope it helps you,
Thierry
The below code snippet is using to call my web service using restful API.
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
String uri= "https://127.0.0.1:8443/cas-server-webapp-3.5.0/login";
WebResource resource = client.resource(URLEncoder.encode(uri));
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("username", "suresh");
queryParams.add("password", "suresh");
resource.queryParams(queryParams);
ClientResponse response = resource.type(
"application/x-www-form-urlencoded").get(ClientResponse.class);
String en = response.getEntity(String.class);
System.out.println(en);
And getting this exception while running the above code
com.sun.jersey.api.client.ClientHandlerException: java.lang.IllegalArgumentException: URI is not absolute
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:151)
at com.sun.jersey.api.client.Client.handle(Client.java:648)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:680)
I googled many articles and did'nt get where i am doing wrong .
Side note :cas-server-webapp-3.5.0 war deployed on my machine in Apache tomacat7
An absolute URI specifies a scheme; a URI that is not absolute is said to be relative.
http://docs.oracle.com/javase/8/docs/api/java/net/URI.html
So, perhaps your URLEncoder isn't working as you're expecting (the https bit)?
URLEncoder.encode(uri)
For others who landed in this error and it's not 100% related to the OP question, please check that you are passing the value and it is not null in case of spring-boot: #Value annotation.
The problem is likely that you are calling URLEncoder.encode() on something that already is a URI.
Maybe the problem only in your IDE encoding settings. Try to set UTF-8 everywhere:
In an API Key Authorization Scenario...
You may be performing the 2nd REST call after getting an AUTH_TOKEN and ENDPOINT_URL from the first REST call.
Check your concatenation of "<ENDPOINT_URL> + <API_METHOD_URI>", you may be sending only the API_METHOD_URI.
This happened to me using the Streamsets integration platform trying to connect to Oracle's Responsys API.
For me, I was getting this error, when configuation in yaml files, which composed my URL was changed. oops,
I recently moved over to Java and am attempting to write some REST tests against the netflix REST service.
I'm having an issue in that my response using rest assured either wants to send a gzip encoded response or "InputStream", neither of which provide the actual XML text in the content of the response. I discovered the "Accept-Encoding" header yet making that blank doesn't seem to be the solution. With .Net I never had to mess with this and I can't seem to find the proper means of returning a human readable response.
My code:
RestAssured.baseURI = "http://api-public.netflix.com";
RestAssured.port = 80;
Response myResponse = given().header("Accept-Encoding", "").given().auth().oauth(consumerKey, consumerSecret, accessToken, secretToken).param("term", "star wars").get("/catalog/titles/autocomplete");
My response object has a "content" value with nothing but references to buffers, wrapped streams etc. Trying to get a ToString() of the response doesn't work. None of the examples I've seen seem to work in my case.
Any suggestions on what I'm doing wrong here?
This has worked for me:
given().config(RestAssured.config().decoderConfig(DecoderConfig.decoderConfig().noContentDecoders())).get(url)
I guess in Java land everything is returned as an input stream. Using a stream reader grabbed me the data I needed.
Until its version 1.9.0, Rest-assured has been providing by default in the requests the header "Accept-Encoding:gzip,deflate" with no way of changing it.
See
https://code.google.com/p/rest-assured/issues/detail?id=154
It works for me:
String responseJson = get("/languages/").asString();
I am calling a restful service that returns JSON using the Apache HttpClient.
The problem is I am getting different results in the encoding of the response when I run the code on different platforms.
Here is my code:
GetMethod get = new GetMethod("http://urltomyrestservice");
get.addRequestHeader("Content-Type", "text/html; charset=UTF-8");
...
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
StringWriter writer = new StringWriter();
IOUtils.copy(response.getEntity().getContent(), writer);
When I run this on OSX, asian characters etc return fine e.g. 張惠妹 in the response. But when I run this on a linux server the same code displays the characters as ???
The linux server is an Amazon EC2 instance running Java 1.6.0_26-b03
My local OSX is running 1.6.0_29-b11
Any ideas really appreciated!!!!!
If you look at the javadoc of org.apache.commons.io.IOUtils.copy(InputStream, Writer):
Copy bytes from an InputStream to chars on a Writer using the default
character encoding of the platform.
So that will give different answers depending on the client (which is what you're seeing)
Also, Content-Type is usually a response header (unless you're using POST or PUT). The server is likely to ignore it (though you might have more luck with the Accept-Charset request header).
You need to parse the content type's charset-encoding parameter of the response header, and use that to convert the response into a String (if it's a String you're actually after). I expect Commons HTTP has code that will do that automatically for you. If it doesn't, Spring's RESTTemplate definitely does.
I believe that the problem is not in the HTTP encoding but elsewhere (e.g. while reading or forming the answer). Where do you get the content from and how? Is this stored in a DB or file?
I am developing an application that uses restful api. A java client sending a request to a standalone server is throwing Unsupported Media Type exception.
The client code is as follows
StringBuilder xml = new StringBuilder();
xml.append("<?xml version=\"1.0\" encoding=\"${encoding}\"?>").append("\n");
xml.append("<root>").append("\n");
xml.append("<user>").append("\n");
xml.append("<username>"+username+"</username>");
xml.append("\n");
xml.append("<password>"+pass+"</password");
xml.append("\n");
xml.append("</user>");
xml.append("</root>");
Representation representation = new StringRepresentation(xml.toString());
new ClientResource("http://localhost:7777/Auth").post(representation);
Server code is as follows
new Server(Protocol.HTTP,7777,TestServer.class).start();
String username = (String) getRequest().getAttributes().get("username");
String password=(String) getRequest().getAttributes().get("password");
StringRepresentation representation = null;
You are not passing the content-type header; I strongly recommend using an API like Apache Common HttpClient to produce such requests (and maybe read the contents from a file).
#Riccardo is correct, the Restlet Resource on the server is checking the Content-Type header of the client's request to make sure the entity you're POSTing to the server has a type it can support. Here's a Restlet 1.1 example. You'll notice that that Resource is set up to expect XML:
// Declare the kind of representations supported by this resource.
getVariants().add(new Variant(MediaType.TEXT_XML));
So maybe your server side doesn't declare the representations it can handle, or it does and Restlet's automatic media type negotiation is detecting that your request doesn't have Content-Type: text/xml (or application/xml) set.
So as #Riccardo suggests, use Apache HttpClient and call HttpRequest.setHeader("Content-Type", "text/xml"), or use Restlet's client library API to do this (it adds another abstraction layer on top of an HTTP client connector like Apache HttpClient).