Android HTTP Connection with Remote Database - android

I am having an Android Activity which I want to connect with MYSql database with JSP page as middle layer to accept values from android and do query on databse.
Problem is I'm not able to send parameter values from Android Activity to JSP page. Application crashes as Emulator starts. I have given permission for internet in manifest file, This catches exception.
public void tryLogin() {
Log.v(TAG, "Trying to Login");
EditText etxt_user = (EditText) findViewById(R.id.txt_username);
EditText etxt_pass = (EditText) findViewById(R.id.txt_password);
String username = etxt_user.getText().toString();
String password = etxt_pass.getText().toString();
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8084/authen/register.jsp");
List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
nvps.add(new BasicNameValuePair("username", username));
nvps.add(new BasicNameValuePair("pass", password));
try {
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,"utf-8");
httppost.setEntity(p_entity);
HttpResponse response = client.execute(httppost);
Log.v(TAG, "Sahil Sahil Sahil");
Log.v(TAG, response.getStatusLine().toString());
HttpEntity responseEntity = response.getEntity();
Log.v(TAG, "Set response to responseEntity");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
LoginHandler myLoginHandler = new LoginHandler();
xr.setContentHandler(myLoginHandler);
xr.parse(retrieveInputStream(responseEntity));
ParsedLoginDataSet parsedLoginDataSet = myLoginHandler.getParsedLoginData();
if (parsedLoginDataSet.getExtractedString().equals("SUCCESS")) {
// Store the username and password in SharedPreferences after the successful login
SharedPreferences.Editor editor=mPreferences.edit();
editor.putString("UserName", username);
editor.putString("PassWord", password);
editor.commit();
Message myMessage=new Message();
myMessage.obj="SUCCESS";
handler.sendMessage(myMessage);
} else if(parsedLoginDataSet.getExtractedString().equals("ERROR")) {
Intent intent = new Intent(getApplicationContext(), LoginError.class);
intent.putExtra("LoginMessage", parsedLoginDataSet.getMessage());
startActivity(intent);
removeDialog(0);
}
} catch (Exception e)
{
Intent intent = new Intent(getApplicationContext(), LoginError.class);
intent.putExtra("LoginMessage", "Unable to login");
startActivity(intent);
removeDialog(0);
}
}

Here you have a small example how to send parameters to a URL...
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
....
String data = URLEncoder.encode("param1", "UTF-8") + "="
+ URLEncoder.encode(param1, "UTF-8");
data += "&" + URLEncoder.encode("param2", "UTF-8") + "="
+ URLEncoder.encode(param2, "UTF-8");
URL url = new URL(http://example.com);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();

You can create a JSP page that accepts an XML parameter in GET format, and do operation on that data.
Example:
You create a page like this, which will accept XML formatted data:
http://example.com/api/getdb.jsp?data=XML_FORMATED_DATA
Suppose you have the following XML data:
String sXML = "<xml>" +
"<table>" +
"<row>" +
"<name>Alice</name>" +
"<salary>5000</salary>" +
"</row>" +
"<row>" +
"<name>Bob</name>" +
"<salary>7000</salary>" +
"</row>" +
"</table>" +
"</xml>" ;
Now you just do this in your Android code:
String sUrlEncoded = UrlEncoder.encode(sXML, "utf-8"); // This line encodes XML symbols into URL-friendly characters.
URL url = new URL("http://example.com/api/getdb.jsp?data=" + sUrlEncoded);
URLConnection conn = url.openConnection();
That's all...!
Now you've called your JSP page with the XML data as the GET parameter. In your JSP, you need to retrieve the XML data, and parse it, and perform the operation!
Just like: (I am trying some JSP!)
String pXML = request.getParameter("data");
// Now parse the content of pXML variable!
Tip:
For added security, you can include a spot-generated session-key to the URL like this:
http://example.com/api/getdb.jsp?userid=USER_SESSION_KEY&data=XML_FORMATED_DATA

Working example from my code...
Android
HttpPost post = new HttpPost("http://localhost:8080//AddLocation.jsp");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("id", "007"));
pairs.add(new BasicNameValuePair("name", "James Bond");
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
JSP
request.getParameter("id");
request.getParameter("name");

Related

android Django rest API,authentication

A friend have a Rest API with Django, and Im trying to make and android app for it, but I having problems with the authentication.
First i get the CSRF token, just making a get call and taking the value.
public String getCFSRToken() throws Exception{
String csrftokenValue="";
httpClient.execute(new HttpGet(urlBasic));
cookieStore = httpClient.getCookieStore();
List <Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie: cookies) {
Log.v("csrftoken",cookie.getName());
if ( cookie.getName().compareTo("csrftoken")==0) {
csrftokenValue = cookie.getValue();
}
}
return csrftokenValue;
}
Then I try to make the authentication:
public void login3() throws Exception{
String urlLogin ="/login";
String url = urlBasic+urlLogin;
String username = "jesus.m.martinez.garcia";
String password = "lolofree";
String userpass = username +":"+password;
HttpPost post = new HttpPost(url);
// List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// nameValuePairs.add(new BasicNameValuePair("username", username));
// nameValuePairs.add(new BasicNameValuePair("password", password));
// post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String basicAuth = "Basic " + new String(Base64.encode(userpass.getBytes(),Base64.NO_WRAP ));
post.addHeader("Authorization", basicAuth);
post.addHeader("X-CSRFToken", getCFSRToken());
HttpResponse response = httpClient.execute(post);
CookieStore as = httpClient.getCookieStore();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
String pagina="";
while ((line = rd.readLine()) != null) {
pagina= pagina + "\n"+line;
}
System.out.println(pagina);
}
If I don't add the CSRF header I receive always a 403 Forbidden, so I suppose that part is correct, but when I try to do the login with the post (as you can see I have try without codification and basic), I always receive a 200 Ok, but I receive an HTML page for logging and I don't get the session cookie, that's what is killing me.
I asked my friend and he told me, he didn't modify the authentication of Django framework, so I suppose is not digest. Any idea what I am doing wrong?
Thank you in advance ;)

Android webview send image using postUrl

I'm working on an android app which uses webview and what I'm trying to accomplish is to successfully pass a base64 encoded image on my php file by using post.Url() and then display it on html5 canvas.
I have no difficulty in my php file (web) my problem is with this:
String url = "http://localhost/folder/postImage.php";
String encodedImage = iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==";
String postData = "image=data:image/png;base64," + encodedImage;
webview.postUrl(url,EncodingUtils.getBytes(postData, "BASE64"));
So, basically that's how my coding works, what I need is to retain the value of postData and not encode it to BASE64 again since it is already encoded in BASE64.
Instead of this :
webview.postUrl(url,EncodingUtils.getBytes(postData, "BASE64"));
What should i put in here:
webview.postUrl(url,EncodingUtils.getBytes(postData, "???????"));
Hope you'll help me with my problem or at least suggest. THANK YOU! :)
HTTP.UTF_8
I run it through http post base 64 and php.
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://www.mywebsite.com/foo.php";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("image", image_str));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,
HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Log.i("RESPONSE", EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}

Receiving Data on the servlet From Android?

I am trying to send data to from my android app to the servlet using POST method but servlet don't show any kind of the activity just null has shown in the output. Although I am receiving response from servlet on the android app using GET method.
We try to print action on logcat. It shows that data has been sent but show null on browser.
I am also receiving exception "Invalid use of single client connection manager:Connection still allocated"
Android Code:-
String url = "http://10.0.2.2:8084/AndroidApp/AndroidServlet";
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost httpPost = new HttpPost(url);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Name", name));
nameValuePairs.add(new BasicNameValuePair("Father", father));
nameValuePairs.add(new BasicNameValuePair("Gender", gender));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
String response = httpClient.execute(httpPost, res);
}
Servlet Code:-
public class AndroidServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
String Name=request.getParameter("Name");
String Father=request.getParameter("Father");
String Gender=request.getParameter("Gender");
try (PrintWriter out = response.getWriter()) {
out.println("Hello Android !!!!");
out.println( Name + " " + Father + " " + Gender + " ");
}
}
Output on Browser:-
Hello Android !!!!
null null null
It's difficult to debug net apps without external tools and of course it will be difficult to find bug in your code without compiling it.
For debugging such apps I use Android Emulator + WireShark to look at the body of HTTP request. Hope it'll help.
Edited:
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try{
String strResponseSaveGoal =
httpclient.execute(httppost, responseHandler);
Log.d("sendCancelOrderRequest", strResponseSaveGoal);
}catch ( ConnectTimeoutException conEx )
{
handler.sendEmptyMessage(CANCEL_REQUEST_ERROR);
}
catch (ClientProtocolException ex) {
Log.d("sendCancelOrderRequest","");
handler.sendEmptyMessage(CANCEL_REQUEST_ERROR);
}catch (IOException ex) {
Log.d("sendCancelOrderRequest","");
handler.sendEmptyMessage(CANCEL_REQUEST_ERROR);
}

How to parse this specific XML from HttpResponse in Android?

I'm new in Android development. I made an Android app for login in a website. The login page takes three inputs 'username', 'password' & 'pin'.
I've successfully passed these data using HttpPost method. See the code,
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mysite.com/api/service.php");
try {
// Add user name, password & pin
String action = "login";
EditText uname = (EditText)findViewById(R.id.txt_username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.txt_password);
String password = pword.getText().toString();
EditText pcode = (EditText) findViewById (R.id.txt_pin);
String pin = pcode.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("action", action));
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("pin", pin));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("PS", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Now i want to parse the 'ack' & 'msg' from HttpResponse which is a XML output appears after passing data to the website. See here,
<login>
<member>
<id/>
<username/>
<name/>
<ewallpoints/>
<ack>FAILED</ack>
<msg>Wrong Username and Password</msg>
</member>
</login>
Use response.getEntity().getContent() to get an input stream and process it with DOM, SAX or XPath as #tobias suggested. There are many options.
You may also get the xml string directly. Change the line
HttpResponse response = httpclient.execute(httppost);
to
String xml = httpclient.execute(httppost, new BasicResponseHandler());

http post successfully logged in?

I am trying to login to a webside which needs 3 parameters in the post command.
Token, usr_name and usr_password.
The token always has the following value "545616f1e29bc538843ec7aa908122b1e".
I am getting this value by doing a HttpGet on the loginpage and store it as a string.
If i do a login through the url as follows https://www.xxxxx.com/xxxx/restricted/form/formelement=0123?usr_name=myuser&usr_password=mypass&token=545616f1e29bc538843ec7aa908122b1e the login succeeds.
How do i get a.m link build together and know afterwards that i successfully logged in?
Thanks for any tips and helping me out.
My code:
try {
String webPage = "https://xxxxxxxx.com/xx/Authenticationserv";
String name = username; // user input through editbox
String password1 = password; // user input through editbox
String authString = name + ":" + password1 + ":" + token + "=" + value;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBytesToBytes(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb1 = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb1.append(charArray, 0, numCharsRead);
}
String result = sb1.toString();
System.out.println("/// BEGIN ///");
System.out.println(result);
System.out.println("/// END ///");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Actually I think you need to use POST method to log in in your website.I had the same problem a few weeks ago and I've did this :
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> postParameters;
httpclient = new DefaultHttpClient();
httppost = new HttpPost("your login link");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username_hash", "fcd86e8cc9fc7596f102de7b2b922e80c6e6fac9"));
postParameters.add(new BasicNameValuePair("password_hash", "b66936348bd0bd44fa44f5ca7dcceb909545e47f"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.toString());
So you are setting up your post params with an ArrayList and you can get the responce from the server if you logged in via HttpResponse.And another thing : I'm setting up the username and password in the code,because it is just to how you the idea.If you have any questions feel free to ask.
Hope it helps!

Categories

Resources