I want to first say that I am a newbie to Android and java (to a lesser extent). I have a client-server application, the client is an Android app and the server is running Tomcat. Considering I am new at this I am a little confused about the POST request. The Client has a couple text fields, the user enters information and hits a button that calls on a method that well does a POST task. I can see that the server receives the data from the POST form in the client but my question is where does that information (from the form) go? It is supposed to create a new resource (in this case a Person resource)...Here is the code from the PersonResource class that does the POST.
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces(MediaType.APPLICATION_JSON)
public Person postPerson(MultivaluedMap<String, String> personParams) {
String firstName = personParams.getFirst(FIRST_NAME);
String lastName = personParams.getFirst(LAST_NAME);
String email = personParams.getFirst(EMAIL);
System.out.println ("System storing: " + firstName + " " + lastName + " " + email);
person.setFirstName(firstName);
person.setLastName(lastName);
person.setEmail(email);
System.out.println ("person info: " + person.getFirstName() + " " + person.getLastName() + " " + person.getEmail() + " " + person.getId());
return person;
}
It returns a person resource but ultimately where does that person resource go? I am sorry if I have not provided all required information needed to solve this problem. If more information is needed I will be happy to provide it. I truly appreciate any help given. Thank you.
I am not sure I fully understand the question, but here is an overview that might be helpful:
The client POST sends an HTTP request to the server. The server must have some sort of web service framework (e.g. Jersey or CXF or ...) that processes the request. The JAX-RS annotations on your class (#POST and #Consume), instruct the web service framework to route the request to the postPerson method of your class. It sounds like this much is working, yes?
Your method then constructs a Person object based upon the contents of the form, i.e. the user input. Your method returns this Person to the web service framework.
So what happens to this person? The #Produces annotation you have provided, instructs the web service framework to generate a JSON representation of the person and include this in the body of the HTTP response that is sent back to the client. The response might look something like this:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 259
{"fistName":"Bob", "lastName":"Barker", "email":"bob_bark#priceisright.com"}
Is this what you were looking for?
You can use HttpPost to submit the request and then use gson to convert the response back to object. The HttpPost should be placed under async request (i.e AsyncTask). You can refer
http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
Async HTTP post android
http://code.google.com/p/google-gson/
Related
I have to call a web service located in http://ip:port/ws which has no wsdl.
I can send an HTTP POST using Spring framework's RestTemplate and get answer as raw input from the service. But this is annoying a bit, that's why I am looking for the correct way to consume this web service without WSDL.
Can anybody suggest a 'best practice' way for this task?
There is really no best practice, recreating the WSDL or at least the XML Schema seems like your only option to improve upon your current approach.
If you're really lucky, it'll return some consistent XML that you might be able to throw an XPath parser at to extract the bits you need. You might be able to tease out the XML schema either from the data it returns (look for a namespace declaration at the top of the document somewhere, and see if you can follow the URI it references), or drop the data into an on-line schema generator like this one
I could not find the best solution, and did some workaround. So as we know the SOAP call in HTTP environment is a standard HTTP POST with the soap envelope in HTTP POST body. So I did the same. I stored the xml soap requests in different place just not mess with the code:
public static final String REQ_GET_INFO = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:xyz\">" +
" <soapenv:Header/>" +
" <soapenv:Body>" +
" <urn:export>" +
" <cardholderID>%s</cardholderID>" +
" <bankId>dummy_bank</bankId>" +
" </urn:export>" +
" </soapenv:Body>" +
"</soapenv:Envelope>";
And in service layer I used RestTemplate post call with required headers:
#Value("${service.url}") // The address of SOAP Endpoint
private String wsUrl;
public OperationResponse getCustomerInfo(Card card) {
OperationResponse operationResponse = new OperationResponse(ResultCode.ERROR);
try {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/xml");
HttpEntity<String> request = new HttpEntity<>(String.format(Constants.SoapRequest.REQ_GET_INFO,
card.getCardholderId()), headers);
String result = restTemplate.postForObject(wsUrl, request, String.class);
if(!result.contains("<SOAP-ENV:Fault>")) {
// Do SOAP Envelope body parsing here
}
}
catch(Exception e) {
log.error(e.getMessage(), e);
}
return operationResponse;
}
A little bit of dirty job, but it worked for me :)
Am trying to implement the CCU fast purge call via JAVA and am referencing this doucument
https://developer.akamai.com/api/purge/ccu/reference.html
import javax.ws.rs.core.MediaType;
Client client = ClientBuilder.newClient();
Entity payload = Entity.json("{ 'hostname': 'www.example.com', 'objects': [ '/graphics/picture.gif', '/documents/brochure.pdf' ]}");
Response response = client.target("https://private-anon-3f6068ab95-akamaiopen2ccuccuproduction.apiary-mock.com/ccu/v3/delete/url/{network}")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(payload);
System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
here am getting confused with the objects and the client.target url that needs to be specified.
" objects': [ '/graphics/picture.gif', '/documents/brochure.pdf'
] "
Are these objects and client.target urls will be unique to my application and the account that is going to be created.?
and also is there any thing that i have to pass in headers for the validation or authentications.?
You need to:
Get credentials for your client using Luna (https://control.akamai.com)
Click "Configure... Manage APIs"
Select "CCU APIs" in the left hand side
Create new collection, create new client
Create authorization
Click the "Export" button at the top to grab the credentials, including the URL
Use these credentials and the Java signing client at https://github.com/akamai-open/AkamaiOPEN-edgegrid-java to make the call
There is sample code on the page for the Java signing client showing how to make calls to the system.
I have been trying hard to work this out for login authentication using angular as client and jersey exposed as rest web service at backend.
Here is what I achieved from last three days.
Angular code to capture email and password:
myApp.controller('loginController',['$scope','$http', function($scope, $http)
{
$scope.email = "" ;
$scope.password = "" ;
$scope.loginForm = function(){
alert("login controller called");
console.log($scope.email);
console.log($scope.password);
var encodedString = 'email=' +
encodeURIComponent($scope.email) +
'&password=' +
encodeURIComponent($scope.password);
$http({
method:'POST',
url: 'rs/loginResource',
data: encodedString,
headers: {'Content-Type' : 'application/x-www-form-urlencoded'}
});
};
}]);
Java rest code:
#Path("/loginResource")
public class LoginResource {
public LoginResource() {
}
#POST
#Consumes("application/x-www-form-urlencoded")
public void login(#FormParam("email") String email,
#FormParam("password") String password) {
System.out.println("Email is: " + email); //prints output
System.out.println("Password is: " + password); //prints output
}
}
And now my question is where to go from here after getting the POST data from form submit. As you can see I am just printing the values rather I would like to check the email and password against database(oracle). How would I go about it? Shall I use simple connection class and dao or go for JPA which I haven't learned yet - what is the learning curve for it?
Is there any design pattern involved? Usually I use Dao and pojo if its plain java but I am new to rest api that too struggling with angular. I hardly find any examples on vanilla java+angular where most of them are based on spring+angular.
Generally login goes like this:
Client calls server with login details
Server verifies login details against the database, if valid, sets up a session. If invalid, the server will return a very generic error response. Important to not give the client any info about which part of the submission was wrong (gives attackers more info).
For this you'll want to read into sessions. Here are some links:
https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpSession.html
https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec#.z4vdsyrty
There's plenty of information on this problem on the internet.
Also, for generic REST APIs authentication will usually happen in the form of a token. The flow looks a little different:
Client calls server with some sort of auth info
The server generates a token using something like Json Web Tokens and returns it to the client. Generally these have an expiry. The server might also expire all other tokens for the user.
The client sends the token, generally as a header, with every future request.
There's lots of ways to encrypt a password when sending it from client -> server. Here's a simple one I suggest you try: RESTful Authentication
I am working on a Payment Integration System in Java Rest Api.
The Gateway is Zaakpay. When a user clicks Proceed to payment my site is redirected to Zaakpay payment gateway. After a successful payment from Zaakpay it redirects the user to my returnURL.html. The Transaction Results are sent to returnURL.html as a POST Form Data in a HTTP Request.
How do I capture that POST Form Data in request and how do I forward it to Java Rest Api.
Why payment gateway is returning the result to returnURL.html ?
I think you must have specified somewhere to indicate payment gateway to return result to this URL , So instead you can provide your Controller URL path .
After that in order to intercept the post request you need a method in your controller , So here is an example of Jersey based implementation of JAX-RS
#POST
#Path("/add")
public Response addUser(
#FormParam("name") String name,
#FormParam("age") int age) {
<================Do Whatever you need to do here ====================>
return Response.status(200)
.entity("addUser is called, name : " + name + ", age : " + age)
.build();
}
I looked through the jBPM6 user guide, and I found that there are URL's available for each operation, like: http://serverurl:8080/business-central/rest/task/query?potentialOwner=bpmuser
This URL is used to get the tasks assigned to bpmuser. I'm able to request this URL using Google's REST client without any errors. The problem is though, that I'm getting an authorization error when I try to request this URL from my Java program. Could anybody help me with the problem I'm having?
You can send authentication details in header as below.
String authData = "krisv" + ":" + "krisv";
String encoded = new sun.misc.BASE64Encoder().encode(authData.getBytes());
get.setHeader("Authorization", "Basic " + encoded);
See my answer in this thread for a working example.
Did you read the documentation?
http://docs.jboss.org/jbpm/v6.0.1/userguide/jBPMRemoteAPI.html
Are you sending the user / password?
Look at this section -> 17.1.1. The REST Remote Java RuntimeEngine Factory