Sharing java classes between web-service and client-side - java

I'm programming android app as my final project. It's connecting to a java web-service on cloud.
My problem is that I want to use complex java objects and share them between my android app and my web service on cloud.
As example I have "Mission" class and i want use methods that get "Mission" type argument as parameter, or returns "Mission" type. I want to use those complex objects just as String, Integer or Boolean.
May I create a library or jar file or something that hold those classes on the client side and the server side?
What should I do to use those classes and complex java objects between the server-side and the client-side just as we use String or other regular java types?

The best method is using JSON. That it can not transfer all the data.
URL url = new URL("Your Web Service URL");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
sample :
http://androidexample.com/Restful_Webservice_Call_And_Get_And_Parse_JSON_Data-_Android_Example/index.php?view=article_discription&aid=101&aaid=123

Related

Design pattern for using Auth Tokens?

I'm a client side developer, moving over to server side development.
One common problem I am encountering is the need to make one API call (say to get an authentication token) and then make a follow up API call to get the data I want. Sometimes, I need to make two API calls in succession for data, without an auth token as well.
Is there a common design pattern or Java library to address this issue? Or do I need to manually create the string of calls each time I need to do so?
Edit: I'm hoping for something that looks like this
CustomClassBasedOnJson myStuff = callAPI("url", getResponse("authURL"));
This would make a call to the "url" with data received from the "authURL".
The point here is that I'm stringing multiple url calls, using the result of one call to define the next one.
When doing Server side programming, it is acceptable for HTTP calls to be called synchronously.
Therefore the proper pattern is to simply make the first call, receive the result, and then use that in the next line. There is no need to separate the calls into separate threads, or asynchronous calls, unless there is major processing happening between http calls.
For example:
JsonResponseEntry getJsonReportResponse() throws IOException {
String sReportURL = "https://someurl.com/v2/report/report?" +
"startts=" + getDateYesterday("ts") +
"&endts=" + getDateNow("ts") +
"&auth=" + getAuthCode();
URL reportURL = new URL(sReportURL);
URLConnection conn = reportURL.openConnection();
BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
ObjectMapper mapper = new ObjectMapper();
JsonNode reportResult = mapper.readTree(buf);
return convertJSonNodeToJsonResponseEntry(reportResult);
}
String getAuthCode() throws IOException {
String sReportURL = "https://someurl.com/auth";
URL reportURL = new URL(sReportURL);
HttpURLConnection conn = (HttpURLConnection) reportURL.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
String urlParameters = "username=myUserName&password=mypassword";
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
ObjectMapper mapper = new ObjectMapper();
AuthResponse response = mapper.readValue(buf, AuthResponse.class);
return response.toString();
}
The function getAuthCode() is synchronously called within the URL call that requires the response.

java- how to use gson library to parse a json response+ storing session id so that it can be accessed by javascript functions in gae

I am trying to authenticate to a server's secure URL using java.net.urlconnection - based on the useful tutorial at Using java.net.URLConnection to fire and handle HTTP requests
The response will be as given below--
Return: A session id object: {'session_id': 'username:session_token'}
This session_id will be used for all methods which require authentication.
This response is JSON response, and I am thinking of using the Google GSON library (since my web app is on Google App Engine).
The code I have used so far (based on the tutorial to which I have given link above) is given below--
String url = "https://api.wordstream.com/authentication/login";
String charset = "UTF-8";
String param1 = WORDSTREAM_API_USERNAME;
String param2 = WORDSTREAM_API_PASSWORD;
// ...
String query = String.format("username=%s&password=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
InputStream error = ((HttpURLConnection) connection).getErrorStream();
//now checking HTTP Response status
int status = ((HttpURLConnection) connection).getResponseCode();
How do I proceed further to obtain the JSON response and retrieve session ID from that response correctly?
Another question- I want to store the session ID in session data that can be accessed by javascript functions, because I plan to use javascript functions to make calls and obtain further data. Is this possible, and how to implement this?
Step 1- Create a subclass- declare it as static so that it can be utilised by the GSON library. This subclass should mimic the data contained in a single JSON Response- in our case only the session ID is stored in the response- hence this class contains just one string variable...
static class LR {
public String response;
public LR() {
// No args constructor for LR
}
}
Now, use BUfferedReader and readline to read the entire response and store it in a string variable.
InputStream response = connection.getInputStream();
BufferedReader br = new BufferedReader(new
InputStreamReader(response));
String str="", temp;
while (null != ((temp = br.readLine())))
{
System.out.println (str);
str=str + temp;
}
Finally, invoke 'fromJSON(string, class)' to obtain the value-
Gson gson = new Gson();
LR obj2 = gson.fromJson(str, LR.class);
return(" Session ID="+ obj2.response);

Create Restful Client Consumer with Tomcat

I am using Apache tomcat 6.0.20
I want to create Client To Consume RESTFul Web Service(using GET)
I know I can do it via the old fashion way with URLConnection (regular GET request).
But I wonder is there any way of doing it differently? maybe with Annotations?
I think this article http://www.oracle.com/technetwork/articles/javase/index-137171.html will give you good guidance how to act in both directions.
I'm currently using the API of spring. The connection handling for example is handled already within the RestTemplate class. Have a look to http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/remoting.html#rest-client-access.
Using NetBeans 7 there is the possibility to have RESTFul web services created with a simple wizard (with Jersey API): http://netbeans.org/kb/docs/websvc/rest.html . This approach uses annotations.
In the end I chose to use the JAVA SE API in the old and fashion way:
public void getRestfullMethod(...) throws IOException
{
String temp = null;
//Build the request data.
StringBuffer buf = new StringBuffer (..)
buf.append("&system=").append ("someVal");
String urlStr = buf.toString ();
//Send the request.
URL url = new URL (urlStr);
URLConnection con = url.openConnection();
//Return the response.
BufferedReader in = new BufferedReader (new InputStreamReader (con.getInputStream ()));
String inputLine = null;
buf = new StringBuffer ();
while ((inputLine = in.readLine ()) != null)
buf.append (inputLine);
in.close ();
}

How to post a named variable to a PHP file?

I want to post among other data a String variable to a PHP file by using the HttpConnection stuff. The first data is the byte[] data returned from a recordstore. So it should be posted alone. So how to post the String variable also ?
You can pass the data to a PHP file using GET or POST methods.
Get method is the easy way to pass simple data. Using GET you can add the variable to the URL
Example:
192.168.1.123/myproject/uploads/treatphoto.php?myVariable1=MyContent&myVariable2=MyContent2
And in PHP:
$content1 = $_GET['myVariable1'];
$content2 = $_GET['myVariable2'];
Also the content of "MyContent" needs to be an string encoded. using any UrlEncoder.
To pass a byte[] array using this method you need to convert the byte array to an string encoded in some printable encoding like base64
The GET method also has a sort limit of data that can be passed safely (usually 2048 bytes)
The other method "POST" is more complex (but not a lot), way to add more data.
You need to prepare the HttpConnection to pass the data as POST.
Also the data stored in urlParamenters need to be according to the url enconding.
Passing the data using post is similar to GET but instead of adding all the variables next to the url the varuiables are added in the Stream of the httpConnection request.
example of the java code:
String urlParameters = "myVariable1=myValue1&myVariable2=myValue2";
HttpURLConnection connection = null;
try {
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
// Use post and add the type of post data as URLENCODED
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// Optinally add the language and the data content
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
// Set the mode as output and disable cache.
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
// Get Response
// Optionally you can get the response of php call.
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
The php is similar, you only need to replace $_GET by $_POST:
$content1 = $_POST['myVariable1'];
$content2 = $_POST['myVariable2'];

Java connecting to Http which method to use?

I have been looking around at different ways to connect to URLs and there seem to be a few.
My requirements are to do POST and GET queries on a URL and retrieve the result.
I have seen
URL class
DefaultHttpClient class
HttpClient - apache commons
which method is best?
My rule of thumb and recommendation: Don't introduce dependencies and 3rd party libraries if it's fairly easy to get away without.
In this case I would say, if you need efficiency such as multiple requests per established connection session handling or cookie support etc, go for HTTPClient.
If you only need to perform an HTTP get, this will suffice:
Getting Text from a URL
try {
// Create a URL for the desired page
URL url = new URL("http://hostname:80/index.html");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Sending a POST Request Using a URL
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
Both methods work great. (I've even done manual gets/posts with cookies.)
HTTPClient is the way to go if your needs go past trivial URL connection (e.g. proxy authentication such as NTLM). There are at least a comparison here between standard HTTP client functionality between libraries provided by the JRE, Apache HTTP Client and others.
If you are using JDK versions earlier to (including 1.4) and have a fairly large data in your post requests, like large file uploads, the default HTTPURLConnection that comes with the JRE is bound to go Out of memory at some point since it buffers the entire data before posting. Additionally it does not support some advanced HTTP headers like chunked encoding, etc.
So I'd recommend it only if your request are trivial and you are not posting large data as aioobe did.

Categories

Resources