how to pass data from servlet to android application - java

I have a form in android upon submit im inserting it into database using servlet i have to show to user that form was inserted successfully. this is my application
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
/**
*
* #author trainee
*/
public class form extends HttpServlet {
String name;
String password;
Connection con = null;
Statement stmt = null;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
/* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet form</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet form at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try
{
}
catch(Exception ex)
{
}
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try
{
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/Login","root", "");
String nn=request.getParameter("name");
String pass=request.getParameter("pass");
String email=request.getParameter("email");
stmt=con.createStatement();
String query="insert into users values('"+nn+"','"+pass+"','"+email+"');";
int v=stmt.executeUpdate(query);
ArrayList<String> arr=new ArrayList<String>();
arr.add("inserted");
System.out.println("sent response back...");
}
catch(Exception ex)
{
}
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
this is my android application
package org.me.loginandroid;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.methods.HttpGet;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1 = (Button) findViewById(R.id.submit);
btn1.setOnClickListener(listener_login);
}
private OnClickListener listener_login = new OnClickListener() {
boolean check = false;
public void onClick(View v) {
EditText emailText = (EditText) findViewById(R.id.email);
EditText passText = (EditText) findViewById(R.id.password);
EditText nameText = (EditText) findViewById(R.id.uname);
String name = nameText.getText().toString();
String email = (emailText.getText().toString());
String pass = (passText.getText().toString());
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
nameValuePairs.add(new BasicNameValuePair("email", email));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8084/Login/form");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
TextView lbl = (TextView) findViewById(R.id.lbl);
lbl.setText(result);
} catch (Exception e) {
TextView tv = (TextView) findViewById(R.id.err);
tv.setText("Error parsing data " + e.toString());
System.out.println("Error parsing data " + e.toString());
}
//parse json data
try {
boolean check=false;
ArrayList<String> arrays=new ArrayList<String>();
for(int i=0;i<arrays.size();i++)
{
if(arrays.get(i).equals("Inserted"))
{
check=true;
}
else
{
}
}
if(check)
{
Intent myintent = new Intent(MainActivity.this, welcome.class);
startActivity(myintent);
}
else
{
TextView tv = (TextView) findViewById(R.id.err);
tv.setText("Data was not inserted properly");
}
} catch (Exception e) {
//setContentView(R.layout.notify);
TextView tv = (TextView) findViewById(R.id.err);
tv.setText(e.toString());
System.out.println("log_tag" + "Error parsing data ");
}
}
};
}

You need to make a URLConnection to your servlet page and do it. Example for it: How to download file/image from url to your device

you can get data from servlet to andriod application through json format.
Please go through this
http://wiebe-elsinga.com/blog/?p=405 link to get an idea of how to call Servlet from andriod application and get the response
back in json format.
call to Servlet from Andriod
private InputStream callService(String text) {
InputStream in = null;
SERVLET_URL = http://wizkid.com/web/updateServlet";
try {
URL url = new URL(SERVLET_URL);
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("POST");
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.connect();
DataOutputStream dataStream = new DataOutputStream(conn
.getOutputStream());
dataStream.writeBytes(text);
dataStream.flush();
dataStream.close();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
display("Error: Not not connect");
}
return in;
}
// Get Data from Server to andriod
private String getResultFromServlet(String text) {
String result = "";
InputStream in = callService(text);
if (in != null) {
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(convertStreamToString(in));
result = jsonResponse.getString("output");
} catch (JSONException e) {
result = "Error: JSON Object couldn't be made";
}
} else {
result = "Error: Service not returning result";
}
return result;
}

first of all,
if your doGet() and doPost() do the same thing, you can call one from the other, sending the request and response
Second, you can pass an ArrayList<E> to the android app.
Both the Servlet and Android APIs have it
edit:
You need to read from a InputStream, generated by a HttpURLConnection object.
http://developer.android.com/reference/java/io/InputStream.html
check out this book:
used book http://www.amazon.com/Professional-Android-Application-Development-Programmer/dp/0470565527)
String input = getString(R.string.input);
try {
URL url = new URL(input);
URLConnection connection = url.openConnection();
HttpURLConnection http = (HttpURLConnection)connection;
int response = http.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
InputStream is = http.getInputStream();
//do whatever you want with the stream
}
}
catch (MalformedURLException exception) { }
catch (IOException exception) { }

You can check here. There is a whole description with sample code
Send arraylist from servlet to Android application

Related

Webpage login error-Android App

I'm new to Android and Java. I'm creating an app to login to my ISP. This is the page: http://reliancebroadband.co.in/reliance/login.do
Earlier, I was using a python script, which worked flawlessly. Its like this:
#!/usr/bin/env python
# encoding: utf-8
import urllib2, urllib, cookielib
username = 'my-username'
password = 'my-password'
jar = cookielib.FileCookieJar("cookies")
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
response = opener.open("http://reliancebroadband.co.in/reliance/startportal_isg.do")
login_data = urllib.urlencode({'userId' : username, 'password' : password, 'action' : 'doLoginSubmit'})
resp = opener.open('http://reliancebroadband.co.in/reliance/login.do', login_data)
And now i'm trying to create an android app(source: http://www.compiletimeerror.com/2013/01/login-application-for-android.html#.U7AFBPmSz9Y) (Tried contacting the developer there, but he's not responding.)
The app is compiling correctly, but while tring to login, its just returning the source code of the login page in the error dialogue, instead of logging in.
Here's the code:
MainActivity.java:
package com.app.reliancebblogin;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#SuppressLint("NewApi")
public class MainActivity extends Activity
{
EditText un, pw;
TextView error;
Button ok;
private String resp;
private String errorMsg;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
un = (EditText) findViewById(R.id.et_un);
pw = (EditText) findViewById(R.id.et_pw);
ok = (Button) findViewById(R.id.btn_login);
error = (TextView) findViewById(R.id.tv_error);
ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
/** According with the new StrictGuard policy, running long tasks on the Main UI thread is not possible
So creating new thread to create and execute http operations */
new Thread(new Runnable()
{
#Override
public void run()
{
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",un.getText().toString()));
postParameters.add(new BasicNameValuePair("password",pw.getText().toString()));
String response = null;
try
{
response = SimpleHttpClient.executeHttpPost("http://reliancebroadband.co.in/reliance/login.do", postParameters);
String res = response.toString();
resp = res.replaceAll("\\s+", "");
}
catch (Exception e)
{
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try
{
/** wait a second to get response from server */
Thread.sleep(1000);
/** Inside the new thread we cannot update the main thread
So updating the main thread outside the new thread */
error.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty())
{
error.setText(errorMsg);
}
}
catch (Exception e)
{
error.setText(e.getMessage());
}
}
});
}
}
SimpleHttpClient.java:
package com.app.reliancebblogin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class SimpleHttpClient
{
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient()
{
if (mHttpClient == null)
{
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* #param url The web address to post the request to
* #param postParameters The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}

Communicate between android Application and java

Every body i am new in program world , I am getting a issue,My Request is related to Communication between Android tablet to Desktop PC using JAVA Code.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello Android !!!!");
}
}
above code is my servlet code which is running in my local system server (Tomcat 6.0 ) here i am sending message through println and i want to reveive same message in my Android app which is running in another system. Now i am going to post my android code which is running on another system.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HttpGetServletActivity3 extends Activity implements
OnClickListener {
Button button;
TextView outputText;
public static final String URL =
"http://192.168.0.2:9999/HttpGetServlet/HelloWorldServlet";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#Override
protected void onPostExecute(String output) {
outputText.setText(output);
}
}}
Here 192.68.0.2 is ip address of system where servlet code is running in my local system (Tomcat6.0 server which has port no 9999) .But it is not working for me.Both the system are in same wifi network Any help is really very appreciated. Thanks in advance to all
try this i will work for you. This is android code
protected Integer doInBackground(String... arg0) {
/** According with the new StrictGuard policy, running long tasks on the Main UI thread is not possible
So creating new thread to create and execute http operations */
new Thread(new Runnable() {
#Override
public void run() {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",un.getText().toString()));
postParameters.add(new BasicNameValuePair("password",pw.getText().toString()));
String response = null;
try {
response = SimpleHttpClient.executeHttpPost("http://XXX.168.1.X:5555/LoginServlet/loginservlet.do", postParameters);
res = response.toString();
System.out.println("response :"+res);
} catch (Exception e) {
// e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
/** Inside the new thread we cannot update the main thread
So updating the main thread outside the new thread */
try {
}catch (Exception e) {
error.setText(e.getMessage());
// e.printStackTrace();
}
return null;
}
Now this is another class for android
public class SimpleHttpClient {
public static String result="";
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* #param url The web address to post the request to
* #param postParameters The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
// String str1= request.setEntity(formEntity);
System.out.println("actual request"+formEntity);
HttpResponse response = client.execute(request);
System.out.println("response in class"+response);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
}catch(Exception e){
e.printStackTrace();
System.out.println("catch");
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
String result="";
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
}
catch(Exception e){
e.printStackTrace();
System.out.println("catch2");
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}}
And finally this is servlet code for you
public class LoginServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String un,pw;
un=request.getParameter("username");
pw=request.getParameter("password");
System.out.println("username :"+un);
System.out.println("password :"+pw);
if(un.equals("") || pw.equals("") ){
out.print("null");
}
else if(un.equalsIgnoreCase("hello") && pw.equals("world"))
{
out.print("success");
}
else{
out.print("failed");
}
System.out.println("after :");
request.getAttribute("USER"+un);
request.getAttribute("PASS"+pw);
RequestDispatcher rd=request.getRequestDispatcher("home.jsp");
rd.forward(request, response);
}catch(Exception e){
System.out.println("inside exception");
e.printStackTrace();
}
finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
service(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
service(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}}

I am getting Error parsing data org.json.JSONException

I am getting this error in my LogCat:
Error parsing data org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONArray
Below are every file I could show you! Please let me know the problem and its solution ASAP. What I guess is:
1. Maybe the is problem is with parsing data in JSON array.
2. Maybe the problem is with my php api, I think I am not properly encoding the json_encode because it gives me RAW JSON, like every thing in one line.
as below
[{"uid":"120","name":"MyFirstName MyLastName"}]
Please also let me know, their is some difference in working of both format, 1. Raw JSON and 2. Intented Json
below is the intented json format
[
{
"uid":"120",
"name":"MyFirstName MyLastName"
}
]
Here is the JSONUseActivity.java
package com.example.oncemore;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import com.example.oncemore.CustomHttpClient;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class JSONUseActivity extends Activity {
EditText email,password;
Button submit;
TextView tv; // TextView to show the result of MySQL query
String returnString; // to store the result of MySQL query after decoding
// JSON
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is
// most commonly
// used to catch
// accidental
// disk or
// network
// access on the
// application's
// main thread
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jsonuse);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
submit = (Button) findViewById(R.id.submitbutton);
tv = (TextView) findViewById(R.id.showresult);
// define the action when user clicks on submit button
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// declare parameters that are passed to PHP script i.e. the
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
postParameters.add(new BasicNameValuePair("email",email.getText().toString()));
postParameters.add(new BasicNameValuePair("password",password.getText().toString()));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
"http://mywebsite.com/android/api.php",
postParameters);
// store the result returned by PHP script that runs MySQL
// query
String result = response.toString();
// parse json data
try {
returnString = "";
//I think the line below is creating some problem
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag",
"id: " + json_data.getInt("uid")+", name: " + json_data.getString("name"));
// Get an output to the screen
returnString += "\n" + json_data.getString("name")
+ " -> " + json_data.getInt("uid");
}
}catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
try {
tv.setText(returnString);
}
catch (Exception e) {
Log.e("log_tag", "Error in Display!" + e.toString());
;
}
}
catch (Exception e) {
Log.e("log_tag",
"Error in http connection!!" + e.toString());
}
}
});
}
}
Here is the CustomHttpClient.java
package com.example.oncemore;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.util.Log;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the specified
* parameters.
*
* #param url
* The web address to post the request to
* #param postParameters
* The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url
* The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
}
Here is the api.php
<?php
require_once("../contactdb.php");
$myusername=$_REQUEST["email"];
$mypassword=$_REQUEST["password"];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT uid,name FROM u_info WHERE email='".$myusername."' AND password ='".$mypassword."'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
while($row=mysql_fetch_assoc($result))
$output[]=$row;
echo json_encode($output);
mysql_close();
}else{
echo "Error Occured!";
}
?>
Finally, When I goto browser and write like this
http://mywebsite.com/android/api.php?email=myname#yahoo.com&password=1234
I got this json array!
[{"uid":"120","name":"MyFirstName MyLastName"}]
So Far I google, I have found different formats of json array! I found everywhere Intented Json. My json array is currently in Raw Json format. I don't find anywhere how to convert Raw Json format into Intented Json format.
Thanks in advance guys!
Any help would be appreciated! If possible, please provide the correct code!
That is NOT valid JSON syntax:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
Is Valid.
Note: This is also valid:
{"employees": [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" } ] }
The syntax structure is the important part, not the formatting in terms of indentation.
As otherwise said, to use the fomat you're returning, you need to cut the substring from the response, i.e get rid of the square brackets surrounding the braces.
In PHP I create a proper json response as follows:
// array for JSON response
$response = array();
$response["apps"] = array();
$apps = array();
$apps["name"] = $row["name"];
$apps["package"] = $row["package"];
$apps["version"] = $row["version"];
$apps["dateversion"] = $row["dateversion"];
array_push($response["apps"], $apps);
$response["success"] = 1;
echo json_encode($response);
This basically gives
{ "success":"1", "apps":{["name":"NAME", "package":"PACKAGE", "version":"VERSION", "dateversion":"DATEVERSION"]}}
which can be parsed correctly by any of the abundant examples of JSON classes which you can make use of. Hacking and using substring to manually remove the first N characters is NOT good practice...

call java class with click on a button

I am trying to call another class called HttpUtilityTester.java from Mainactivity.java.
Actually I'd like to test HttpUtility.sendPostRequest from HttpUtility.java with a click on a button.
The spot is marked with this comment: "//here I need help from stackoverflow"
This is already added to my button in the activity_main.xml:
android:onClick="sendMessage1"
here is Mainactivity.java:
package com.example.mythirdapp;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
//here I need help from stackoverflow
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
here is HttpUtility.java:
package com.example.mythirdapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class HttpUtility {
/**
* Represents an HTTP connection
*/
private static HttpURLConnection httpConn;
/**
* Makes an HTTP request using GET method to the specified URL.
*
* #param requestURL
* the URL of the remote server
* #return An HttpURLConnection object
* #throws IOException
* thrown if any I/O error occurred
*/
public static HttpURLConnection sendGetRequest(String requestURL)
throws IOException {
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoInput(true); // true if we want to read server's response
httpConn.setDoOutput(false); // false indicates this is a GET request
return httpConn;
}
/**
* Makes an HTTP request using POST method to the specified URL.
*
* #param requestURL
* the URL of the remote server
* #param params
* A map containing POST data in form of key-value pairs
* #return An HttpURLConnection object
* #throws IOException
* thrown if any I/O error occurred
*/
public static HttpURLConnection sendPostRequest(String requestURL,
Map<String, String> params) throws IOException {
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoInput(true); // true indicates the server returns response
StringBuffer requestParams = new StringBuffer();
if (params != null && params.size() > 0) {
httpConn.setDoOutput(true); // true indicates POST request
// creates the params string, encode them using URLEncoder
Iterator<String> paramIterator = params.keySet().iterator();
while (paramIterator.hasNext()) {
String key = paramIterator.next();
String value = params.get(key);
requestParams.append(URLEncoder.encode(key, "UTF-8"));
requestParams.append("=").append(
URLEncoder.encode(value, "UTF-8"));
requestParams.append("&");
}
// sends POST data
OutputStreamWriter writer = new OutputStreamWriter(
httpConn.getOutputStream());
writer.write(requestParams.toString());
writer.flush();
}
return httpConn;
}
/**
* Returns only one line from the server's response. This method should be
* used if the server returns only a single line of String.
*
* #return a String of the server's response
* #throws IOException
* thrown if any I/O error occurred
*/
public static String readSingleLineRespone() throws IOException {
InputStream inputStream = null;
if (httpConn != null) {
inputStream = httpConn.getInputStream();
} else {
throw new IOException("Connection is not established.");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String response = reader.readLine();
reader.close();
return response;
}
/**
* Returns an array of lines from the server's response. This method should
* be used if the server returns multiple lines of String.
*
* #return an array of Strings of the server's response
* #throws IOException
* thrown if any I/O error occurred
*/
public static String[] readMultipleLinesRespone() throws IOException {
InputStream inputStream = null;
if (httpConn != null) {
inputStream = httpConn.getInputStream();
} else {
throw new IOException("Connection is not established.");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
List<String> response = new ArrayList<String>();
String line = "";
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
return (String[]) response.toArray(new String[0]);
}
/**
* Closes the connection if opened
*/
public static void disconnect() {
if (httpConn != null) {
httpConn.disconnect();
}
}
}
here is HttpUtilityTester.java:
package com.example.mythirdapp;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class HttpUtilityTester {public static void main(String[] args) {
// test sending GET request
String requestURL = "http://www.google.com";
try {
HttpUtility.sendGetRequest(requestURL);
String[] response = HttpUtility.readMultipleLinesRespone();
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
HttpUtility.disconnect();
System.out.println("=====================================");
// test sending POST request
Map<String, String> params = new HashMap<String, String>();
requestURL = "https://accounts.google.com/ServiceLoginAuth";
params.put("Email", "your_email");
params.put("Passwd", "your_password");
try {
HttpUtility.sendPostRequest(requestURL, params);
String[] response = HttpUtility.readMultipleLinesRespone();
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
HttpUtility.disconnect();
}
}
I tried to add code of the HttpUtilityTester.java to my Mainactivity.java like this:
...public class MainActivity extends Activity {
public void sendMessage1(View v){
// test sending POST request
Map<String, String> params = new HashMap<String, String>();
requestURL = "https://accounts.google.com/ServiceLoginAuth";
params.put("Email", "your_email");
params.put("Passwd", "your_password");
try {
HttpUtility.sendPostRequest(requestURL, params);
String[] response = HttpUtility.readMultipleLinesRespone();
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
HttpUtility.disconnect();
}...
But logcat sais: "could not execute method of the activity"
The following will be called when you click that button, so place it in your code where applicable.
public void sendMessage1(View v){
}

Java IPN JSP works but Servlet fails

Have been trying to get the IPN response call to work via a servlet. I can use the demo jsp to receive the IPN request and also issue and receive the IPN response.
https://www.paypal.com/us/cgi-bin/webscr?cmd=p/pdn/ipn-codesamples-pop-outside#java
But when I try the same code in a servlet it does not work - the servlet receives the initial IPN request, I am able to pull the request variables but when I shoot them back to paypal the response I get is basically a bunch of HTML and not the typical VERIFIED message. I have surfed for a while and also tried changing my servlet any number of ways to no avail.
Thanks
Here is My servlet Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class PPListen extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8669468768750366974L;
static Logger logger = Logger.getLogger(PPListen.class.getName());
private static final String PAYPAL_TEST_URL = "https://www.sandbox.paypal.com/cgi-bin/webscr";
private static final String PAYPAL_PROD_URL ="https://www.paypal.com/cgi-bin/webscr";
//private HttpClient httpClient;
public PPListen() {
// TODO Auto-generated constructor stub
}
public void service(HttpServletRequest request, HttpServletResponse respose) throws ServletException, IOException {
if (logger.isInfoEnabled()) {logger.info("Into Service ");}
PropertyConfigurator.configure("c:\\D-Drive\\EclipseProjects\\gcms\\WEB-INF\\log4j.conf");
String uri = request.getRequestURI();
String rh = request.getRemoteHost();
System.out.println("URI:"+uri+":");
System.out.println("Remote Host:"+rh+":");
// This is required by PayPal
Enumeration<String> e = request.getParameterNames();
String outStr = "cmd=_notify_validate";
logger.debug("******* Output Data");
while (e.hasMoreElements()) {
String name = e.nextElement();
String val = request.getParameter(name);
outStr = outStr + "&"+name+"="+URLEncoder.encode(val);
if (logger.isDebugEnabled()) {
logger.debug("Received Value Named:"+name+": Value:"+val+":");
}
}
URL u = new URL(PAYPAL_TEST_URL);
URLConnection uc = u.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
PrintWriter pw = new PrintWriter(uc.getOutputStream());
pw.println(outStr);
pw.close();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
logger.debug("******* Output Data");
while (true) {
String result = in.readLine();
if (result == null) {
break;
}
logger.debug(result);
}
logger.debug("******* END");
in.close();
}
/*
public void service2(HttpServletRequest request, HttpServletResponse respose) throws ServletException, IOException {
if (logger.isInfoEnabled()) {logger.info("Into Service ");}
PropertyConfigurator.configure("c:\\D-Drive\\EclipseProjects\\gcms\\WEB-INF\\log4j.conf");
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
String uri = request.getRequestURI();
String rh = request.getRemoteHost();
System.out.println("URI:"+uri+":");
System.out.println("Remote Host:"+rh+":");
// This is required by PayPal
params.add(new NameValuePair("cmd","_notify_validate"));
Enumeration<String> e = request.getParameterNames();
while (e.hasMoreElements()) {
String name = e.nextElement();
String val = request.getParameter(name);
params.add(new NameValuePair(name,val));
if (logger.isDebugEnabled()) {
logger.debug("Received Value Named:"+name+": Value:"+val+":");
}
}
NameValuePair[] uu = (NameValuePair[])params.toArray(new NameValuePair[params.size()]);
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(PAYPAL_PROD_URL);
post.setRequestBody(uu);
if (logger.isDebugEnabled()) {
logger.debug("--- calling parameters out to PayPal are ---");
for (NameValuePair nvp: params) {
logger.debug(" Being Sent - Name:"+nvp.getName()+": Value:"+nvp.getValue());
}
logger.debug("--- end of calling parameters out to PayPal ---");
}
logger.debug("--- Prior to Connect Specific");
logger.debug("--- after Connect Specific");
client.executeMethod(post);
logger.debug("--- after POST");
// String resp = post.getResponseBodyAsString();
int status = post.getStatusCode();
byte[] responseBody = post.getResponseBody();
logger.debug("Value Returned From PayPal is :"+new String(responseBody));
logger.debug("Query String :"+post.getQueryString()+":");
logger.debug("Status Code of call is "+status+":");
}
}
Any help will be great. Thanks

Categories

Resources