I have a Java servlet web server and an android application that communicate with each other. What is the proper way of passing a custom object (EX: User object) from server to android.
Example:
User logs in through android device, the users email and password are sent to the server for authentication. Server now needs to send back to the android device the User object.
If you can attach an example or link to tutorial that would be great.
https://www.youtube.com/watch?v=Gyaay7OTy-w
make a class that extends AsyncTask
implement override methods (Alt+Insert)
In do in background:
Make an http url connection
try {
URL url=new URL(urladdress);
HttpURLConnection con= (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestMethod("POST")
con.setDoOutput(true);
con.setDoInput(true);
return con;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
now download the data from this connection
if(con==null) {
Toast.makeText(ctx,"Connection is null",Toast.LENGTH_LONG).show();
}
try{
InputStream is = new BufferedInputStream(con.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer jsonData= new StringBuffer();
while ((line=br.readLine())!=null)
{
jsonData.append(line+"/n");
}
br.close();
is.close();
return jsonData.toString();
} catch (IOException e) {
e.printStackTrace();
}
now parse this jsonData
try{
JSONArray ja = new JSONArray(jsonData);
JSONObject jo = null;
//parse Data
}
In onPostExecute call the required java file which will receive data
write a script that convert data recived from your server and send data in json format
Note- these code belongs three different classes so don't try copy/paste
Use Retrofit, is quite simple and straightforward.
Retrofit has given almost all the API's to make server call and to receive response. Internally they also use GSON to do the parsing. you can go through the official website you will get more info and a tutorial.
Hope it helps
Related
As you can see from my code, I'm trying to programmatically log into a website using post/get...
I'm using the following code in Java, and it's working awesome.
But when I run this same code on android, the app doesn't work.
If I'm doing some encode its run but with wrong parameters!
So what do I have to do ?
final String httpParams=String.format("__LASTFOCUS=&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTEzOTM5NTcxNjQPZBYCZg9kFgICAQ8WAh4DZGlyBQNsdHIWAgIDDxYCHwAFA2x0chYKAgEPZBYGZg9kFgJmDw8WCB4EVGV4dAUCRU4eCENzc0NsYXNzBR5idG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ContentPlaceHolder1%24UserName=%s&ctl00%24ContentPlaceHolder1%24Password=%s&ctl00%24ContentPlaceHolder1%24LoginButton=Login&ctl00%24hdnCurClientTimeZone=%2B02%3A00",userId,password);
try {
wr = new DataOutputStream($.getOutputStream());
wr.writeBytes(httpParams);
wr.flush();
} catch (IOException e) {
e.printStackTrace();
}
I'm writing a client j2me app that connects to a php based api using a post method. For security purposes the app and the api should interact within a session with a 30 minutes timeout. My problem is that, the application user has to keep on logging in even when the session time out is not yet done. My php code is fine because I've tested it on a browser and it works fine; however but the application fails and I have to keep on logging in. Might I be missing something? These are the headers am sending to the server using my Java app.
String phonenumber = this.phonenumberTextbox.getString();
String password = this.passwordTextBox.getString();
HttpConnection httpConn = null;
String url = "http://192.168.56.1/?action=login-user";
InputStream is;
OutputStream os;
is = null;
os = null;
String sReply = "";
boolean loggedIn = false;
try {
// Open an HTTP Connection object
httpConn = (HttpConnection) Connector.open(url);
// Setup HTTP Request to POST
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
httpConn.setRequestProperty("Accept_Language", "en-US");
//Content-Type is must to pass parameters in POST Request
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
os = httpConn.openOutputStream();
String params;
params = "phonenumber=" + phonenumber + "&password=" + password;
os.write(params.getBytes());
// Read Response from the Server
StringBuffer sb = new StringBuffer();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1) {
sb.append((char) chr);
}
// Web Server just returns stuff
sReply = sb.toString();
} catch (IOException ex) {
System.out.println("Cannot find server");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
}
}
if (os != null) {
try {
os.close();
} catch (IOException ex) {
}
}
if (httpConn != null) {
try {
httpConn.close();
} catch (IOException ex) {
}
}
}
// do something with sReply
Default practice in PHP these days** when dealing for sessions if for PHP to generate a cookie for the client to store. Your java client must store this cookie (called phpsessid by default, but any PHP programmer worth their salt will change the cookie name), and present it in the HTTP headers on subsequent requests.
I'm not very familiar with the HTTP support in Java, but if it's anything like curl it will include options for setting and retrieving cookies.
** It used to be possible to pass session tokens by a query string (a GET parameter) when making the request, but as this was horribly insecure and leaked potentially sensitive information, it's never used any more and may even no longer be available as an option.
I have written a test web crawler class that attempts to search Google, as shown:
public class WebCrawler {
String query;
public WebCrawler(String search)
{
query = search;
}
public void connect()
{
HttpURLConnection connection = null;
try
{
String url = "http://www.google.com/search?q=" + query;
URL search = new URL(url);
connection = (HttpURLConnection)search.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.connect();
BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while((line = read.readLine())!=null)
{
System.out.println(line);
}
read.close();
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch(ProtocolException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
connection.disconnect();
}
}
}
When I try to run it with a test query "test" though, I get a HTTP response 403 error-- what am I missing? This is my first time doing any networking stuff with Java.
403 == forbidden, which makes sense because you're a robot trying to access a part of google that they don't want robots accessing. Google's robots.txt pretty clearly specifies that you shouldn't be scraping /search.
Google provides a search API which allows 100 queries per day. They provide libraries and examples of how to interface with it in most languages, including Java. More than that, you've gotta pay.
I am trying to send the object from applet to struts action class
using object output stream but it gives me a exception java.net.ProtocolException: Cannot write output after reading input.
I created a new instance of URLConnection to giving specific url
and tried to write object in url to send the struts action class from applet
i am calling this method on save button click of applet
public saveDesign()
{
try
{
HttpURLConnection urlConnection = getServletConnection(CallServletConnection.SAVE_DESIGN, null);
// Pragma = no-cache; should be null
if(urlConnection != null && urlConnection.getHeaderFields().get("Pragma") != null)
return false;
OutputStream outstream = urlConnection.getOutputStream();//Exception occur here
ObjectOutputStream objectoutstream = new ObjectOutputStream(outstream);
objectoutstream.writeObject("abc");
objectoutstream.flush();
objectoutstream.close();
System.out.println("vctObjectDetails is write ");
}
catch (MalformedURLException exception) {
exception.printStackTrace();
}
catch(ConnectException exception) {
exception.printStackTrace();
}
catch (IOException exception) {
exception.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
but it doesn't work.
Please gives me some tips if anyone knows how to handle this exception.
It all has to do with the lifecycle of an HTTP request (which is what HttpURLConnection abstracts) - once the request has been sent, you cannot modify it any further - in case you have more data to send, you just make another one.
What is happening underneath is that once you call getHeaderFields() (the response header fields), the 'HttpURLConnection' sends the request and makes the response available.
I don't know what is in 'getServletConnection()', but you could try using 'doOutput()' and not reading from the response, until you have finished writing to the request.
could anyone help me with figuring out why this code isn't working? It's supposed to log into HTS, but it doesn't work. It's not giving me any error messages or anything, just no result at all. Any help would be appreciated.
Here's the code:
import java.net.*;
import java.io.*;
public class Login {
private static URL URLObj;
private static URLConnection connect;
public static void main(String[] args) {
try {
URLObj = new URL("http://www.hackthissite.org/user/login");
connect = URLObj.openConnection();
connect.addRequestProperty("REFERER", "http://www.hackthissite.org");
connect.setDoOutput(true);
}
catch (MalformedURLException ex) {
System.out.println("The URL specified was unable to be parsed or uses an invalid protocol. Please try again.");
System.exit(1);
}
catch (Exception ex) {
System.out.println("An exception occurred. " + ex.getMessage());
System.exit(1);
}
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream()));
writer.write("username=BrandonHeat&password=**********&btn_submit=Login");
writer.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String lineRead = "";
while ((lineRead = reader.readLine()) != null) {
System.out.println(lineRead);
}
reader.close();
}
catch (Exception ex) {
System.out.println("There was an error reading or writing to the URL: " + ex.getMessage());
}
}
}
i'm just guessing, but the documentation for URLConnection indicates that you must connect after having set the parameters :
1.The connection object is created by invoking the openConnection method on
a URL.
2.The setup parameters and general request properties are manipulated.
3.The actual connection to the remote object is made, using the connect
method.
4.The remote object becomes available. The header fields and the contents of
the remote object can be accessed.
...
The following methods are used to
access the header fields and the
contents after the connection is made
to the remote object:
getContent
getHeaderField
getInputStream
getOutputStream
Edit :
can't you open the URL with you parameters in the URL (ie http://www.hackthissite.org/user/login?username=BrandonHeat&password=xxxxx&btn_submit=Login), or setted as header ?
also, after the connect(), what do you get if you do a getContent() ?
Edit : there is a description of the process here.
Regards
Guillaume