Getting an error while trying to consume a Restful web service using
POST method(with form param).
I want to consume a REST application using POST method.
Please find below the resource class I want to access.
#Path("/user")
public class User {
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response get(#FormParam("username") String userName,
#FormParam("userid") String userId ){
}
I tried using Jesry Client for accessing.Please find below the code i tried.
I tried adding values to FormParam as shown below.
Trail 1
WebResource webResource = client.resource("baseURL/user");
String input = "userid:1001,username:demo1";
ClientResponse response = webResource.type("application/x-www-form-urlencoded").post(ClientResponse.class, input);
I am getting a an error response back "The server encountered an internal error () that prevented it from fulfilling this request".
I think I am not adding the values to FormParam properly.
Trial 2
I also tried adding the form params using the below code
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("userid", "1001");
formData.add("username", "demo1");
ClientResponse response = webResource.type("application/x-www-form-urlencoded").post(ClientResponse.class, formData);
This also resulted in the same error.
Trial 3
Form f = new Form();
f.add("userid", "1001D");
f.add("username", "1001D");
ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, f);
This also resulted in the same error.
Any help is appreciated.
Since your error indicates "Server encountered an internal error" you need to look at the server (logs) to see what went wrong. Certainly your 3rd client looks fine to reach the service you defined (assuming you are using something real instead of the string "baseURL").
You can easily test your server is working separately from your client by creating a HTML page to reach the service. Create a HTML form using enctype="application/x-www-form-urlencoded" and posting to your service endpoint (what you are calling "baseURL/user") with form parameters userid and username. When you view the HTML form in a browser and hit the submit button, it will call your server - if you get the same error you can be sure it is nothing to do with your client code.
Hope http://yogeshmprajapati.blogspot.in/2011/12/login-to-fb-from-java.html will help you.
Related
I am building an agent in Java which has to solve games using a planner. The planner that I am using runs as a service on the cloud, and thus anybody can send HTTP requests to it and get a response. I have to send to it a JSON with the following content: {"domain": "string containing the domain's description", "problem": "string containing the problem to be solved"}. As a response I get a JSON that contains the status and the result, which might be a plan or not, depending on whether there was some problem or not.
The following piece of code allows me to call the planner and receive its response, retrieving the JSON object from the body:
String domain = readFile(this.gameInformation.domainFile);
String problem = readFile("planning/problem.pddl");
// Call online planner and get its response
String url = "http://solver.planning.domains/solve";
HttpResponse<JsonNode> response = Unirest.post(url)
.header("accept", "application/json")
.field("domain", domain)
.field("problem", problem)
.asJson();
// Get the JSON from the body of the HTTP response
JSONObject responseBody = response.getBody().getObject();
This code works pefectly fine and I don't have any kind of problem with it. Since I have to do some heavy testing on the agent, I prefer to run the server on localhost, so that the service doesn't get saturated (it can only process one request at a time).
However, if I try to send a request to the server running on localhost, the body of the HTTP request that the server receives is empty. Somehow, the JSON is not sent and I am receiving a response that contains an error.
The following piece of code illustrates how I am trying to send a request to the server running on localhost:
// Call online planner and get its response
String url = "http://localhost:5000/solve";
HttpResponse<JsonNode> response = Unirest.post(url)
.header("accept", "application/json")
.field("domain", domain)
.field("problem", problem)
.asJson();
For the sake of testing, I had previously created a small Python script that sends the same request to the server running on localhost:
import requests
with open("domains/boulderdash-domain.pddl") as f:
domain = f.read()
with open("planning/problem.pddl") as f:
problem = f.read()
data = {"domain": domain, "problem": problem}
resp = requests.post("http://127.0.0.1:5000/solve", json=data)
print(resp)
print(resp.json())
When executing the script, I get a correct response, and it seems that the JSON is sent correctly to the server.
Does anyone know why this is happening?
Okay, fortunately I have found an answer for this issue (don't try to code/debug at 2-3AM folks, it's never going to turn out right). It seems that the problem was that I was specifying what kind of response I was expecting to get from the server instead of what I was trying to send to it in the request's body:
HttpResponse response = Unirest.post(url)
.header("accept", "application/json")...
I was able to solve my problem by doing the following:
// Create JSON object which will be sent in the request's body
JSONObject object = new JSONObject();
object.put("domain", domain);
object.put("problem", problem);
String url = "http://localhost:5000/solve";
<JsonNode> response = Unirest.post(url)
.header("Content-Type", "application/json")
.body(object)
.asJson();
Now I am specifying in the header what type of content I am sending. Also, I have create a JSONObject instance that contains the information that will be added to the request's body. By doing this, it works on both the local and cloud servers.
Despite of this, I still don't really get why when I was calling the cloud server I was able to get a correct response, but it doesn't really matter now. I hope that this answer is helpful for someone who is facing a similar issue!
I'm able call 4-5 rest apis, prior to coming to this block of code. But I'm not able to execute this block of code.
I am using spring 4.0.4 core, mvc jars.
I am trying to call a azure ucwa web service using rest template, its a post method with string as body. I m getting a 500 internal error. I have searched all over internet and yet did not find solution, Please guide me. Thank you.
link : https://learn.microsoft.com/en-us/skype-sdk/ucwa/sendanim
step 9
RestTemplate restTemplate = new RestTemplate();
System.out.println(" jsonLinksObj : 4a "+jsonLinksObj);
org.json.JSONObject jsonSendMessageObj = jsonLinksObj.getJSONObject("sendMessage");
String sendMsgFullUrl = poolUrl.concat(jsonSendMessageObj.getString("href")).concat("?OperationContext=4322131");
headers.clear();
headers.setContentType(MediaType.TEXT_PLAIN);
headers.set("Authorization", "Bearer " + jwtToken);
String body = "My Send Message Here";
HttpEntity<Object> entityJsonSendMsg4 = new HttpEntity<Object>(body, headers);
ResponseEntity<Object> sbSendMsgObj = null;
try{
sbSendMsgObj = restTemplate.exchange(
new URI(sendMsgFullUrl),
HttpMethod.POST,
entityJsonSendMsg4,
Object.class);
} catch(Exception e){
e.printStackTrace();
}
WARN : org.springframework.web.client.RestTemplate - POST request for "https://webpoolpnqin102.infra.lync.com/ucwa/oauth/v1/applications/102086376449/communication/conversations/46db8085-8ad0-4186-a4f0-9a521b256b9b/messaging/messages?OperationContext=4322131" resulted in 500 (Internal Server Error); invoking error handler
org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:589)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:547)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:518)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:463)
at com.test.example.employee.test.EmployeeTest.sendMessage(EmployeeTest.java:266)
at com.test.example.employee.test.EmployeeTest.main(EmployeeTest.java:337)
Exception in thread "main" java.lang.NullPointerException
at com.test.example.employee.test.EmployeeTest.sendMessage(EmployeeTest.java:331)
at com.test.example.employee.test.EmployeeTest.main(EmployeeTest.java:337)
It is hard to say what is the reason behind the 500 you got in response - you probably have to debug it yourself but it should not be very hard.
Since you created RestTemplate using default constructor you have got a deafault error handling. Run your application in debug mode and place a breakpoint in DefaultResponseErrorHandler::handleError. There you get the access to response represented by ClientHttpResponse class and can actually look into body you got back.
When you know the reason behind the error you can correct the request accordingly.
I have clean and build the project. And run the code again. Its working fine, anybody want to send string in body, can use the above rest template code. Thank you.
I created a Jersey client program to consume a REST web service that return XML.
Client client = Client.create();
WebResource webResource = client.resource("http://xyz:abc/myRestservice/getval");
I use the webResource get method to store the return value in a string variable:
String s = webResource.get(String.class);
I get no errors. But variable "s" shows null as output:
System.out.println("- "+s);
Output:
-
Process exited with exit code 0.
When I test the same web service locally (using the JDeveloper IDE without a client program), it returns value.
update:
I found that the variable "s" was showing null because of an exception (explained below) in the web service program.
The web service program uses an opaque (OracleTypes.OPAQUE) variable to store the XMLTYPE value retrieved from a stored function in ORACLE database. The opaque variable is then
assigned to a new XMLType using a cast. This somehow works while testing in JDeveloper IDE internal weblogic server.
But it doesn't work when I deploy this web service in a remote weblogic server and try to consume using a client program.
I get an exception - "oracle.sql.OPAQUE cannot be cast to oracle.xdb.XMLType".
Most probably due to some missing Jar in the remote weblogic server I guess, but not sure which jar.
You are almost there. What you should really be doing is get a ClientResponse.class and not String.class.
Here's a sample:
ClientResponse response = webResource.get(ClientResponse.class);
String responseString = response.getEntity(String.class);
Once you start using this jersey rest client you will know a bit more that per REST api contract, you will also have to set the "requestType" and the "responseAccept" as a part of the webResource. Without that, you might end up having some other weird errors as well.
Here's another sample:
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_XML).post(ClientResponse.class);
String responseStringXML = response.getEntity(String.class);
where:
the request type (data format that the REST API expects in the body) is: "application/json" and
the response type (data format that the REST API returns) is: "application/xml"
Note that I used POST(.post method) instead of get because in normal GET request, a body is not expected (and thus no request Type is needed). The POST example was just for reference. For GET, You will still need a response type though, something along the lines of:
ClientResponse response = webResource.accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
String responseStringXML = response.getEntity(String.class);
I hope that helps !
I have a client-server architecture in REST, Spring MVC. Tghe client is hitting the server URL and sending two parameters along with it. The server is supposed to reply back to the client with a responce value. One the client side I am using RestTemplate to access server URL. When running, the server URL is getting accessed successfully (server side logic is getting executed), but then I am getting the following error on the client side:
HTTP Status 400 -
--------------------------------------------------------------------------------
type Status report
message
description The request sent by the client was syntactically incorrect ().
The client side code is:
rresult = restTemplate.getForObject("http://localhost:8081/Merchant/api/movieTheater"+params.toString(), ResponseText.class);
The esrver side code is:
#ResponseBody
#RequestMapping(value="movieTheater")
public ResponseText getCustomerInput(#RequestParam("name") String name, #RequestParam("price") Double price) {
System.out.println("Requst URL got accessed here");
ResponseText result = new ResponseText();
Transaction transaction = new Transaction();
transaction.setMovieName(name);
transaction.setTicketPrice(price);
transaction.setDatetime(new Date());
if(transactionService.addTransaction(transaction))
result.setMessage(ResponseStatus.SUCCESS.getStatus());
else
result.setMessage(ResponseStatus.FAILED.getStatus());
return result;
}
When I am accessing the URL separately, it is working fine. I am not sure what I am doing wrong. Please help! Thanks in advance!
I figured it out!!! I have an inner class for creating the JSON structure in the client side. The solution is to make that class static! As it was not static, it was trying to instantiate, and hence, got the error message: "Could not read JSON: No suitable constructor found for type"
I guess the URL "http://localhost:8081/Merchant/api/movieTheater"+params.toString() is incorrect. What's the class name of params and what's the result returned by the mothod toString(). getCustomerInput() method can't get the arguments value when incorrect URL accessed.
URL must be like this
http://localhost:8081/Merchant/api/movieTheater?name=xxx&price=1.01
I'm trying to get my contacts from Windows Live using RestEasy
After succesfully authenticating my user, I've made the call to https://livecontacts.services.live.com/users/#L#/rest/livecontacts
Set the authentication header, added my id and my tokens
If i make the call from command line using cUrl I get the expected output, but in my web application I'm getting back gibberish
e.g.
...?{?[??e^7E?...
Current interface class is
public interface WindowsLiveAPI {
#GET
#Path(value="/#L#{liveId}/rest/livecontacts")
Response getContacts(#PathParam("liveId") #Encoded String liveId, #HeaderParam("Authorization") String delegatedToken);
}
ThrowAway test:
ResteasyProviderFactory.getInstance().addMessageBodyReader(DefaultTextPlain.class);
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
WindowsLiveAPI client = ProxyFactory.create(WindowsLiveAPI.class, "https://livecontacts.services.live.com");
ClientResponse<LiveContacts> response = (ClientResponse) client.getContacts(LIVE_ID, DELEGATED_TOKEN);
System.out.println(response.getStatus()); //Produces 200 (401 after token expires)
System.out.println(response.getEntity(String.class)); //produces gibberish
Does anyone have any clue how to unmarshal the response
You could try #Produces(MediaType.APPLICATION_XML) [if it's XML] on the method.