Getting unwanted characters in response from service - java

Getting unwanted characters in response.
I have a simple Restful service that takes objects as input and converts them into JSON string and returns it back. I am using google json api for this task. However all the "=" is getting converted to "\u003d" in the response from the service.
Input to the service:
[{PageViewEvent=PageViewEvent{pageName=Home Page, pageType=Home}}]
Output from service:
"[{PageViewEvent\u003dPageViewEvent{pageName\u003dHome Page, pageType\u003dHome}}]"
Service.java
#POST
#Path("/events")
#Consumes(MediaType.TEXT_PLAIN)
#Produces(MediaType.APPLICATION_JSON)
public String handlePost(String events) {
log.debug("before: " + events);
String jsonResponse = JsonConverter.toJSON(events);
log.debug("atfter: " + jsonResponse);
return jsonResponse;
}
Please guide.

I got rid of the problem by replacing
Gson gson = new Gson();
with
Gson gson = new GsonBuilder().disableHtmlEscaping().create();

Related

How to get raw JSON body in Spring REST controller?

The API below accept a json string from client, and the map it into a Email object. How can I get request body (email) as a raw String? (I want both raw-string and typed version of email parameter)
PS: This question is NOT a duplicate of: How to access plain json body in Spring rest controller?
#PostMapping(value = "/mailsender")
public ResponseEntity<Void> sendMail(#RequestBody Email email) {
//...
return new ResponseEntity<>(HttpStatus.OK);
}
You can do it in more than one way, listing two
1. **Taking string as the paramater**,
#PostMapping(value = "/mailsender")
public ResponseEntity<Void> sendMail(#RequestBody String email) {
//... the email is the string can be converted to Json using new JSONObject(email) or using jackson.
return new ResponseEntity<>(HttpStatus.OK);
}
2. **Using Jackson**
#PostMapping(value = "/mailsender")
public ResponseEntity<Void> sendMail(#RequestBody Email email) {
//...
ObjectMapper mapper = new ObjectMapper();
String email = mapper.writeValueAsString(email); //this is in string now
return new ResponseEntity<>(HttpStatus.OK);
}
Spring uses Jackson for this in the back, you could use it to serialize it to an string. Like so:
#Autowired private ObjectMapper jacksonMapper;
#PostMapping(value = "/mailsender")
public ResponseEntity<Void> sendMail(#RequestBody Email email) {
//...
log.info("Object as String: " + jacksonMapper.writeValueAsString(email));
return new ResponseEntity<>(HttpStatus.OK);
}
you can create json of type string using GSON library
Gson gson = new Gson();
#PostMapping(value = "/endpoint")
public ResponseEntity<Void> actionController(#RequestBody Car car) {
//...
log.info("Object as String: " + this.gson.toJson(car));
return new ResponseEntity<>(HttpStatus.OK);
}
I did not get all things about this question, but I try to answer as I understand. Well,
if you want to get request body:
as you say How to access plain json body in Spring rest controller? here already writen how to do this. If something wrong, maybe you send wrong json or not suitable type as you wite inside Email class. Maybe your request comes url filter
second way try like this:
private final ObjectMapper mapper = new ObjectMapper();
#PostMapping(value = "/mailsender")
public ResponseEntity<Void> sendMail(HttpServletRequest req) {
// read request body
InputStream body = req.getInputStream();
byte[] result = ByteStreams.toByteArray(body);
String text =new String(result,"UTF-8");
//convert to object
Email email = mapper.readValue(body, Email .class);
return new ResponseEntity<>(HttpStatus.OK);
}
If you want to convert object to json string read this post

How to make a POST call using Scribe and fetch data having OAuth 1.0 Authentication in Java?

I have a requirement to make a post-call to a URL which has OAuth 1.0 authentication. I am pretty new to all these. From my research, I got to know about Scribe in Java, but I can find only Get calls using Scribe. I already have consumerKey and consumerSecret key for OAuth 1.0 authentication. Are there any suggestions on how to achieve this successfully.
With postman I am able to fetch the data successfully, but I want to achieve it using Java.
I have tried something like this
I tried this way
public String getSmartCommPDF(#RequestBody Model model) throws IOException {
OAuthService service = new ServiceBuilder().provider(ModelAPI.class).apiKey(consumerKey)
.apiSecret(consumerSecret).build();
OAuthRequest request = new OAuthRequest(Verb.POST, url);
ObjectMapper mapper = new ObjectMapper();
request.addHeader("Content-Type", "application/json;charset=UTF-8");
request.addPayload(mapper.writeValueAsString(model));
Token accessToken = new Token("", ""); // not required for context.io
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println("Response = " + response.getBody());
return "Success";
}
This is my ModelAPI class
public class ModelAPI extends DefaultApi10a {
#Override
public String getRequestTokenEndpoint() {
return "https://domain/one/oauth1/api/v6/job";
}
#Override
public String getAccessTokenEndpoint() {
return "https://domain/one/oauth1/api/v6/job";
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return "https://domain/one/oauth1/api/v6/job";
}
}
This part of code is not throwing any error but, the response body is empty. Where I am going wrong, any one has any idea?
Thank you.
The data was coming back in the input stream. So, I used
response.getStream();
and write it to a file and use it.

Error - Returning JSON along with HTTP status code error JAX-RS

#POST
#Consumes({MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_JSON})
#Path("/data/services")
public Response DiscoverDevice(BlockDevsPost blockdevice) {
for (DeviceIdentifier device : blockdevice.getDevice()) {
String dev = device.Device();
System.out.println("DEVICE "+ dev);
if (dev == null || dev.equals("")){
return Response.status(Response.Status.BAD_REQUEST).entity("Device cannot be null or empty.").build();
}
}
}
Getting this error when fired POST from REST Client when dev is null. I am not able to get JSON and this error is thrown:
Unexpected character (D) at position 0. Device Identifier cannot be null or empty.
Where D in Device Identifier marked as Red which means it is not returning JSON as response.
Your client is expecting to get JSON but you have set a plain string in the Response entity and application/json as content-type. You need to return a valid JSON. For example
return Response
.status(Response.Status.BAD_REQUEST)
.entity("{\"error\":\"Device cannot be null or empty.\"}")
.build();
You can also build the json response string using your preferred mapper (you will need to add a dependency). This is an example using Jackson
Jackson using API
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("error", "Device cannot be null or empty.");
String json = mapper.writeValueAsString(objectNode);
Jackson using POJO
class ErrorBean{
private String error;
//getters and setters
}
ObjectMapper mapper = new ObjectMapper();
ErrorBeanerrorBean = new ErrorBean();
errorBean.setError ("Device cannot be null or empty.");
String json = mapper.writeValueAsString(errorBean);
You can also return POJO from your service method and let the JAX-RS implementation to convert them to JSON (this means change the response type). See https://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/

Java Jersey Web Service: consume JSON request

I have a web service made witj Java and Jersey. I want to receive a JSON request and parse the json for savethe values stores on the json on the database.
This is mi web service code:
#Path("companies")
public class Companies {
#Path("add")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public JSONObject addCompanies(JSONObject inputJsonObj){
String input = (String) inputJsonObj.get("company");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj;
}
}
The client side is made with AngularJS:
$scope.company = "";
$scope.submit = function(){
// Writing it to the server
//
var dataObj = {
company : $scope.company
};
var res = $http.post('http://localhost:8080/WS-Test2/crunchify/companies/add', dataObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
notify("succes");
});
res.error(function(data, status, headers, config) {
//alert( "failure message: " + JSON.stringify({data: data}));
notify("fail");
});
};
This is the error I'm getting when I pass the JSON to the web service:
Status Code:415
And this is the request I am sending:
{"company":"Testing2"}
This is my Network tab:
Without further configuration, JSONObject is not something that Jersey supports. You will just need to work with Strings
public String addCompanies(String json){
JSONObject inputJsonObj = new JSONObject(json)
String input = (String) inputJsonObj.get("company");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj.toString();
}
If you really want to use JSONObject you can check out this post.
See Also:
JAX-RS Entity Providers to learn how Jersey handle serialization an deserialization.

wrong encoding in jaxrs post method

I'm having an Encoding problem when trying to consume an Arabic json message, however when producing the json in a get method I get the message right here is the code:
#Path("/json")
public class HelloJson {
#GET
#Path("/get")
#Produces("application/json; charset=UTF-8")
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle("الليله");
track.setSinger("عمرو دياب");
return track;
}
#POST
#Path("/post")
#Consumes("application/json; charset=UTF-8")
public Response createTrackInJSON(Track track) throws UnsupportedEncodingException{
String result = new String (("Track saved : " + track).getBytes(), "UTF-8");
System.out.println(result);
return Response.status(201).entity(result).type("text/plain; charset=UTF-8").build();
}
}
you can try this webservice on the following link:
http://java7learning-khalidspace.rhcloud.com/rest/json/get
if asked for authentication use username admin and password admin
this link will return you a json with Arabic values without any Encoding problems.
now take this json message and use it in the post method using the following link:
http://java7learning-khalidspace.rhcloud.com/rest/json/post
you can use the post method using the webservice tester from eclipse or any other webservice just insert the content-type=application/json and authorization = Basic YWRtaW46YWRtaW4= as request headers and but the json in the request body.
the post method will return a massage with the arabic characters as "????"
please tell me what I'm missing and thanks for help.
Already have you tried to send them with the escaped characters?:
{
"title" : "\u0627\u0644\u0644\u064A\u0644\u0647",
"singer" : "\u0639\u0645\u0631\u0648 \u062F\u064A\u0627\u0628"
}
I get with this way using SoapUI and your http://java7learning-khalidspace.rhcloud.com/rest/application.wadl:
Track saved : Track [title=الليله, singer=عمرو دياب]

Categories

Resources