Java IPN JSP works but Servlet fails - java

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

Related

Java Refreshing Auth token after 30 min

I want to know how to keep refreshing token every 30 min. Currently i dont have it. I need to cache that token for 30 min and then replace current token with the new refresh token.
Right now when i pass 1000 records all records uses same Auth token but the program runs more than 1 hour. I get Auth token expired error for some of the records.
Can anyone help me with how to handle that scenario ?
Thanks in advance
This is call class and will be calling token class.
package main.java.com.test;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import com.google.common.base.Stopwatch;
public class Call {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws IOException
{
new Call().execute();
}
public String execute() throws IOException {
String number = "01";
String id = "0123456789";
String cd = "107BC0000X";
Token getToken = new Token();
String token = null;
try {
token = getToken.Token();
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("access token" + token);
return token;
}
}
This is another class called Token
package main.java.com.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jettison.json.JSONObject;
public class Token {
private final String USER_AGENT = "Mozilla/5.0";
public String Token() throws Exception
{
Token http = new Token();
http.sendGet();
String token = http.sendPost();
return token;
}
private String sendPost() throws Exception
{
String url = "https://YOUR_AUTH0_DOMAIN/oauth/token";
HttpClient client = new DefaultHttpClient();
HttpClient httpClient1 = wrapClient(client);
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent" , "Mozilla/5.0");
List urlParam = (List) new ArrayList();
urlParam.add(new BasicNameValuePair("client_id", ""));
urlParam.add(new BasicNameValuePair("grant_type", ""));
urlParam.add(new BasicNameValuePair("client_secret", ""));
post.setEntity(new UrlEncodedFormEntity(urlParam));
HttpResponse response = httpClient1.execute(post);
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null){
result.append(line);
}
String[] JsonTags0 = result.toString().split(",");
String[] JsonTags1 = result.toString().split(":");
String token1 = JsonTags1[1].trim();
return token1.substring(1,37);
}
private void sendGet()
{
}
public static HttpClient wrapClient(HttpClient base)
{
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager1();
ctx.init(null, new TrustManager[] {tm},null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ClientConnectionManager ccm = base.getConnectionManager(ctx , SSLSocketFactory , ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf , 443));
return new DefaultHttpClient(ccm, base.getParams());
}
catch (Exception ex){
ex.printStackTrace();
return null;
}
}
}

Parsing cookies to client side

Trying to access the cookies in my DownloadDemo class (downloads information on a website in a csv file) but can't seem to find the correct method to do so. My code:
import java.io.*;
import java.net.URL;
import javax.servlet.*;
import javax.servlet.http.*;
public class DownloadDemo extends CookieTest
{
public static void main(String[] args)
{
StringBuilder contents = new StringBuilder(4096);
BufferedReader br = null;
try
{ //goes to the given URL
String downloadSite = ((args.length > 0) ? args[0] : "google.com");
// file saved in your workspace
String outputFile = ((args.length > 1) ? args[1] : "test.csv");
URL url = new URL(downloadSite);
InputStream is = url.openConnection().getInputStream();
br = new BufferedReader(new InputStreamReader(is));
PrintStream ps = new PrintStream(new FileOutputStream(outputFile));
String line;
String newline = System.getProperty("line.separator");
while ((line = br.readLine()) != null)
{
contents.append(line).append(newline);
}
ps.println(contents.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try { if (br != null) br.close(); } catch(IOException e) { e.printStackTrace(); }
}
}
}
Cookies class:
import java.io.*;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieTest extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
//Get the current session ID by searching the received cookies.
String cookieid = null;
Cookie[] cookies = req.getCookies();
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies[i].getName().equals("REMOTE_USER"))
{
cookieid = cookies[i].getValue();
break;
}
}
}
System.out.println("Cookie Id--"+cookieid);
//If the session ID wasn't sent, generate one.
//Then be sure to send it to the client with the response.
}
//Gets the cookie
public void getCookieUsingCookieHandler() {
try {
// Instantiate CookieManager;
// make sure to set CookiePolicy
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
// get content from URLConnection;
// cookies are set by web site
URL url = new URL("https://google.com");
URLConnection connection = url.openConnection();
connection.getContent();
// get cookies from underlying
// CookieStore
CookieStore cookieJar = manager.getCookieStore();
List <HttpCookie> cookies =
cookieJar.getCookies();
for (HttpCookie cookie: cookies) {
System.out.println("CookieHandler retrieved cookie: " + cookie);
}
} catch(Exception e) {
System.out.println("Unable to get cookie using CookieHandler");
e.printStackTrace();
}
}
public void setCookieUsingCookieHandler() {
try {
// instantiate CookieManager
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
CookieStore cookieJar = manager.getCookieStore();
// create cookie
HttpCookie cookie = new HttpCookie("UserName", "John H");
// add cookie to CookieStore for a
// particular URL
URL url = new URL("https://google.com");
cookieJar.add(url.toURI(), cookie);
System.out.println("Added cookie using cookie handler");
} catch(Exception e) {
System.out.println("Unable to set cookie using CookieHandler");
e.printStackTrace();
}
}
}
Reason for why i'm using cookies is that i need to access the users credentials in order to download the information.
Many thanks in advance.

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();
}
}
}
}
}

how to pass data from servlet to android application

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

Android project using httpclient --> http.client (apache), post/get method

I'm doing a Get and Post method for an android project and I need to "translate" HttpClient 3.x to HttpClient 4.x (using by android).
My problem is that I'm not sure of what I have done and I don't find the "translation" of some methods...
This is the HttpClient 3.x I have done and (-->) the HttpClient 4.x "translation" if I have found it (Only parties who ask me problems) :
HttpState state = new HttpState (); --> ?
HttpMethod method = null; --> HttpUriRequest httpUri = null;
method.abort(); --> httpUri.abort(); //httpUri is a HttpUriRequest
method.releaseConnection(); --> conn.disconnect(); //conn is a HttpURLConnection
state.clearCookies(); --> cookieStore.clear(); //cookieStore is a BasicCookieStore
HttpClient client = new HttpClient(); --> DefaultHttpClient client = new DefaultHttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(SOCKET_TIMEOUT) --> HttpConnectionParams.setConnectionTimeout(param, SOCKET_TIMEOUT);
client.setState(state); --> ?
client.getParams().setCookiePolicy(CookiePolicy.RFC_2109); --> HttpClientParams.setCookiePolicy(param, CookiePolicy.RFC_2109);
PostMethod post = (PostMethod) method; --> ?
post.setRequestHeader(...,...); --> conn.setRequestProperty(...,...);
post.setFollowRedirects(false); --> conn.setFollowRedirects(false);
RequestEntity tmp = null; --> ?
tmp = new StringRequestEntity(...,...,...); --> ?
int statusCode = client.executeMethod(post); --> ?
String ret = method.getResponsBodyAsString(); --> ?
Header locationHeader = method.getResponseHeader(...); --> ?
ret = getPage(...,...); --> ?
I don't know if that is correct.
This has caused problems because the packages are not named similarly, and some methods too.
I just need documentation (I haven't found) and little help.
Here are the HttpClient 4 docs, that is what Android is using (4, not 3, as of 1.0->2.x). The docs are hard to find (thanks Apache ;)) because HttpClient is now part of HttpComponents (and if you just look for HttpClient you will normally end up at the 3.x stuff).
Also, if you do any number of requests you do not want to create the client over and over again. Rather, as the tutorials for HttpClient note, create the client once and keep it around. From there use the ThreadSafeConnectionManager.
I use a helper class, for example something like HttpHelper (which is still a moving target - I plan to move this to its own Android util project at some point, and support binary data, haven't gotten there yet), to help with this. The helper class creates the client, and has convenience wrapper methods for get/post/etc. Anywhere you USE this class from an Activity, you should create an internal inner AsyncTask (so that you do not block the UI Thread while making the request), for example:
private class GetBookDataTask extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(BookScanResult.this);
private String response;
private HttpHelper httpHelper = new HttpHelper();
// can use UI thread here
protected void onPreExecute() {
dialog.setMessage("Retrieving HTTP data..");
dialog.show();
}
// automatically done on worker thread (separate from UI thread)
protected Void doInBackground(String... urls) {
response = httpHelper.performGet(urls[0]);
// use the response here if need be, parse XML or JSON, etc
return null;
}
// can use UI thread here
protected void onPostExecute(Void unused) {
dialog.dismiss();
if (response != null) {
// use the response back on the UI thread here
outputTextView.setText(response);
}
}
}
The easiest way to answer my question is to show you the class that I made :
public class HTTPHelp{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
private boolean abort;
private String ret;
HttpResponse response = null;
HttpPost httpPost = null;
public HTTPHelp(){
}
public void clearCookies() {
httpClient.getCookieStore().clear();
}
public void abort() {
try {
if(httpClient!=null){
System.out.println("Abort.");
httpPost.abort();
abort = true;
}
} catch (Exception e) {
System.out.println("HTTPHelp : Abort Exception : "+e);
}
}
public String postPage(String url, String data, boolean returnAddr) {
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +
"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpPost.setHeader("Accept", "text/html,application/xml," +
"application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
try {
response = httpClient.execute(httpPost,localContext);
} catch (ClientProtocolException e) {
System.out.println("HTTPHelp : ClientProtocolException : "+e);
} catch (IOException e) {
System.out.println("HTTPHelp : IOException : "+e);
}
ret = response.getStatusLine().toString();
return ret;
}
}
I used this tutorial to do my post method and thoses examples
Well, you can find documentation on that version of HTTPClient here; it's especially useful to go through the example scenarios they present.
I unfortunately don't know version 3 of HTTPClient so I can't give direct equivalences; I suggest you take what you're trying to do and look through their example scenarios.
package com.service.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class WebServiceDemoActivity extends Activity
{
/** Called when the activity is first created. */
private static String SOAP_ACTION1 = "http://tempuri.org/GetSubscriptionReportNames";//"http://tempuri.org/FahrenheitToCelsius";
private static String NAMESPACE = "http://tempuri.org/";
private static String METHOD_NAME1 = "GetSubscriptionReportNames";//"FahrenheitToCelsius";
private static String URL = "http://icontrolusa.com:8040/iPhoneService.asmx?WSDL";
Button btnFar,btnCel,btnClear;
EditText txtFar,txtCel;
ArrayList<String> headlist = new ArrayList<String>();
ArrayList<String> reportlist = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnFar = (Button)findViewById(R.id.btnFar);
btnCel = (Button)findViewById(R.id.btnCel);
btnClear = (Button)findViewById(R.id.btnClear);
txtFar = (EditText)findViewById(R.id.txtFar);
txtCel = (EditText)findViewById(R.id.txtCel);
btnFar.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//Use this to add parameters
request.addProperty("Fahrenheit",txtFar.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION1, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
{
//Get the first property and change the label text
txtCel.setText(result.getProperty(0).toString());
Log.e("err ","output is :::: "+result.getProperty(0).toString());
parseSON();
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
txtCel.setText("");
txtFar.setText("");
}
});
}
private void parseSON() {
headlist.clear();
reportlist.clear();
String text = txtCel.getText().toString() ;//sb.toString();
Log.i("######", "###### "+text);
try{
JSONObject jobj = new JSONObject(text);
JSONArray jarr = jobj.getJSONArray("Head");
for(int i=0;i<jarr.length();i++){
JSONObject e = jarr.getJSONObject(i);
JSONArray names = e.names();
for(int j=0;j<names.length();j++){
String tagname = names.getString(j);
if (tagname.equals("ReportID")) {
headlist.add(e.getString("ReportID"));
}
if (tagname.equals("ReportName")) {
reportlist.add(e.getString("ReportName"));
}
}
}
} catch(JSONException e){
Log.e("retail_home", "Error parsing data "+e.toString());
}
Log.d("length ", "head lenght "+headlist.size());
Log.d("value is ", "frst "+headlist.get(0));
Log.d("length ", "name lenght "+reportlist.size());
Log.d("value is ", "secnd "+reportlist.get(0));
}
}

Categories

Resources