Java Jersey Web Service: consume JSON request - java

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.

Related

Adding a new subscriber to a Mailchimp audience using Java and a Jersey Client

I need to add a subscriber to a mailchimp audience. I am using Java and a Jersey client. I have no trouble fetching the members of the audience using the Mailchimp 3.0 API. What must I change about my post request in order to successfully add a new subscriber? When my code fails, there is no response. Then, when I check the Mailchimp account and see that no new subscriber was added.
class MailchimpClient {
Client client;
String mailchimpUrl;
public MailchimpClient() {
String mailchimpApikey = getAPIKey();
String datacenter = mailchimpApikey.substring(mailchimpApikey.lastIndexOf('-') + 1);
mailchimpUrl = "https://" + datacenter + ".api.mailchimp.com/3.0/";
JacksonJsonProvider jjp = new JacksonJsonProvider();
jjp.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ClientConfig conf = new ClientConfig();
conf.property(ClientProperties.CONNECT_TIMEOUT, TIMEOUT);
conf.property(ClientProperties.READ_TIMEOUT, TIMEOUT);
conf.register(jjp);
HttpAuthenticationFeature httpAuth = HttpAuthenticationFeature.basic("username", mailchimpApikey);
client = ClientBuilder.newClient(conf).register(httpAuth);
}
public <T> T get(String path, Class<T> responseType) {
T t = client.target(mailchimpUrl).path(path).request(MediaType.APPLICATION_JSON).get(responseType);
client.close();
return t;
}
public <T> T post(String path, Object payload, Class<T> responseType) {
Entity<Object> entity = Entity.entity(payload, MediaType.APPLICATION_JSON);
T t = client.target(mailchimpUrl).path(path).request(MediaType.APPLICATION_JSON).post(entity, responseType);
client.close();
return t;
}
String audienceid = xxxxxxx;
MailchimpClient mcc = new MailchimpClient();
MembersResponse mr = mcc.get("lists/" + audienceid + "/members", MembersResponse.class);
addToMailchimpAudience(String audienceid);
private Message addToMailchimpAudience(String audienceid) {
HashMap<String, String> newMember = new HashMap<String, String>();
newMember.put("email_address", "bob#gmail.com");
newMember.put("status", "subscribed");
MailchimpClient mcc = new MailchimpClient();
MembersResponse mr = mcc.post("lists/" + audienceid + "/members", newMember, MembersResponse.class);
logger.info("response: " + mr);
return Message.success("Successfully added new member to mailchimp audience");
}
The request to add new members should be a JSON
Add a Contact to a List/Audience
To add a contact to a list/audience, send a POST request to the List Members endpoint: /3.0/lists/9e67587f52/members/. The request body should be a JSON object that contains the information you want to add, with status and any other required list fields.
{
"email_address": "urist.mcvankab#freddiesjokes.com",
"status": "subscribed",
"merge_fields": {
"FNAME": "Urist",
"LNAME": "McVankab"
}
}
I observed you are sending values in a HasMap, trying converting into a JSON and see if it works
Link for your reference:
https://developer.mailchimp.com/documentation/mailchimp/guides/manage-subscribers-with-the-mailchimp-api/

Jersey Client returns HTTP 204 in a post method while trying to send jsonObject

Hey so I'm trying to send some json-object to a rest web service, then get the value of some specific keys, then process the data to finally return a new json-object which is going to be used in another place. Anyway, I'm getting HTTP 204 when I try to communicate with the service.
My rest service looks like this
#Path("/example")
public class PdfMaker {
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response PruebasMet(JSONObject json) throws IOException, JSONException{
try{
String xml = json.getString("xml");
String plantilla = json.getString("plant");
//method that uses "xml" and "plant" and returns "pdf"
JSONObject response = new JSONObject();
response.put("pdf", pdf);
return Response.status(200).entity(pdfb64.toString()).build();
}catch(Exception e){
e.getStackTrace();
return null;
}
}
and I'm trying to communicate with this
public class Jersey {
public static String baseuri = "http://localhost:8080/PdfMakerGF/rest/example/post";
public static void main(String[] args) {
try {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource(baseuri);
JSONObject objTest = new JSONobject();
objTest.put("xml","Data1");
objTest.put("plan", "Data2");
ClientResponse res = webResource.header("Content-Type","application/json;charset=UTF-8")
.post(ClientResponse.class, objTest.toString());
System.out.println("output..." + "\n");
System.out.println("Answer "+res);
} catch (Exception e) {
e.printStackTrace();
}
}
But the response that I receive is this one
Answer POST http://localhost:8080/PdfMakerGF/rest/example/post
returned a response status of 204 No Content
Obviously there is something wrong but can't see what is it.
Since I'm stuck with this. Any kind of help would be appreciated.
I'm using netbeans 8.1, Glassfish 4.1 and Jersey.
Thanks
If your server runs into an exception and goes to the catch block, it returns null which corresponds to HTTP 204 (No Content). As sisyphus commented, there should be some exception in the server standard output.
So you probably need to:
Return a different response code (e.g. INTERNAL_SERVER_ERROR or
BAD_REQUEST) in the catch block
Check why the server code is throwing
the exception
Most likely you get an Exception. I guess it is because you have "plant" in one place and "plan" in another.
okey so finaly it works what i need to change was the way that the service was reciving the data, with a inner class in my case, end up working like this ..
Class Aux{
String xml;
String plant;
//generate gettes and setters :)
}
#Path("/example")
public class PdfMaker {
#POST
#Path("/post")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response PruebasMet(Aux json) throws IOException,
JSONException{
try{
String xml = json.getXml();
String plant = json.getPlant();
//method that uses "xml" and "plant" and returns "pdf"
JSONObject response = new JSONObject();
response.put("pdf", pdf);
return Response.status(200).entity(pdf)).build();
}catch(Exception e){
e.getStackTrace();
return null;
}
}
and the client is ..
Client client = new Client();
WebResource wresource = client.resource("http://localhost:8080/PdfMakerGF/rest/example/post");
JSONObject json = new JSONObject();
json.put("xml", DATA);
json.put("plant", DATA);
ClientResponse response =
wresource.type("application/json").post(ClientResponse.class,
json.toString());
out = response.getEntity(String.class);
System.out.println("RES = "+response);
System.out.println("OUT = "+out);
out has the info that the service is Providing

How to pass array of variables to REST URL in android?

I have to make registration using REST URL. REST services are written in Java now i have to pass the set of parameters in that secGameIds parameter is like this [100,102]. Example registration using Insomnia:::
{
"firstName":"parent111",
"lastName":"sadfsdf",
"email":"abc#bbc.com",
"date":"2000-06-09",
"phoneNum":"8765654454",
"gender":"male",
**"secGameIds":[0,0],**
"roleId":102
}
How should i provide secGameIds parameter value is it a ArrayList or Array?
for remaining values i have created JSONObject class object and adding values to that object and 'm appending that object to url
{
JSONObject json = new JSONObject();
json.put("fistName","aaa");
..
..
HttpPost post = new HttpPost(uri);
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
DefaultHttpClient client = new DefaultHttpClient();
httpresponse = client.execute(post);
}
where as for secGameId i have tried like below,
{
int[] secGameId = {100,102};
}
-- gives me an error in back-end like "nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of int[] out of VALUE_NUMBER_INT token"
I even tried by using
{
ArrayList<Integer> secGameId = new ArrayList<String>();
secGameId.add(100);
secGameId.add(102);
}
and passing to value...
{
json.put("secGameIds":secGameId)
}
again at server side i kicked with the same error.
Can anyone help me?
public static String httpPost(HashMap<String, String> map, String url,String token) {
Log.e("call ", "running");
HttpRequest request;
if(token!=null){
request = HttpRequest.post(url).accept("application/json")
.header("Authorization", "Token " + AppInfo.token).form(map);
}
else
request = HttpRequest.post(url).accept("application/json").form(map);
int responseCode = request.code();
String text = request.body();
Log.e("response", " "+responseCode+ " "+ text);
if(responseCode==400){
return "invalid_tocken";
}
else if(responseCode<200 || responseCode>=300) {
return "error";
}
return text;
}
Hope you can convert the JSONArray to HashMap. If you instead need to post it as a JSONArray itself, then OkHttp library will help you.

http .success() method never called, even when web service got hit

Here is my angular app.js code
$http({
method: 'GET',
url: 'http://localhost:8080/GngWebservice/rest/GngService/FeetToInch'
//webservice url
}).success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
console.log(data);
$scope.data = data || "Request failed";
$scope.status = status;
});
and my rest web service (java) using jersey) method is :
#Path("/FeetToInch")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getoutput() throws JSONException {
JSONObject json=new JSONObject();
JSONObject HEADER=new JSONObject();
JSONObject RESPONSE=new JSONObject();
json.put("name", "hello");
HEADER.put("status","200");
RESPONSE.put("data", "hello");
json.append("HEADER", HEADER);
json.append("RESPONSE", RESPONSE);
String results=""+json;
System.out.println(results);
return Response.status(200).entity(results).build();
}
want ot send json as a response but it always show failed
can any body tell me how to find which error occurred

Getting unwanted characters in response from service

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();

Categories

Resources