Sending POST from Android Application - java

I'm triyng to send POST request to the server. The following java code working for PC application, but doesn't work on my Android application. The Iternet permission is added, so, what I have to do to send this post, and what other methods and libraries I have to use to replace this code for Android?
String hostname = "xxxxxxx.box";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket sock = new Socket(addr, port);
String SID = new classSID("xxxxxx").obtainSID();
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
String str = "enabled=on&username="+givenName+"&email="+givenEmail+"&password="+givenPassword+"&frominternet=on&box_admin_rights=on&phone_rights=on&homeauto_rights=on&uid=&sid="+SID+"&apply=";
////////////////////////////////////////////////////////////////////////////////////////////
wr.write("POST /system/boxuser_edit.lua HTTP/1.1");
wr.write("Host: xxxxxx:80" + "\r\n");
wr.write("Accept: text/html" + "\r\n");
wr.write("Keep-Alive: 300" + "\r\n");
wr.write("Connection: Keep-Alive" + "\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded"+"\r\n");
wr.write("Content-Length: "+str.length()+"\r\n");
wr.write("\r\n");
wr.write(str+"\r\n");
wr.flush();
////////////////////////////////////////////////////////////////////////////////////////////
BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream(),"UTF-8"));
String line;
while((line = rd.readLine()) != null)
Log.v("Response", line);
wr.close();
rd.close();
sock.close();
}

The issue is with creating socket on port 80. You need root permission to access port < 1024 in android. See issue

Try this: and consider using an IP instead of hostname because your android device might nto be able to resolve a local hostname
private static final String UTF_8 = "UTF-8";
/**
* #param hostNameOrIP
* : the host name or IP<br/>
* #param webService
* : the web service name<br/>
* #param classOrEndPoint
* : the file or end point<br/>
* #param method
* : the method being called<br/>
* #param parameters
* : the parameters to be sent in the message body
* #return
*/
public static String connectPOST(final String url, final HashMap<String, String> parameters) {
final StringBuilder postDataBuilder = new StringBuilder();
if (null != parameters) {
for (final HashMap.Entry<String, String> entry : parameters.entrySet()) {
if (postDataBuilder.length() != 0) {
postDataBuilder.append("&");
}
postDataBuilder.append(entry.getKey()).append("=").append(entry.getValue());
}
}
final StringBuffer text = new StringBuffer();
HttpURLConnection conn = null;
OutputStream out = null;
InputStreamReader in = null;
BufferedReader buff = null;
try {
final URL page = new URL(url);
conn = (HttpURLConnection) page.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
out = conn.getOutputStream();
final byte[] postData = postDataBuilder.toString().getBytes(UTF_8);
out.write(postData);
out.flush();
out.close();
final int responseCode = conn.getResponseCode();
if ((responseCode == 401) || (responseCode == 403)) {
// Authorization Error
Log.e(TAG, "Authorization error in " + url + "(" + postDataBuilder.toString() + ")");
// throw new Exception("Authorization Error in " + method + "("
// + postDataBuilder.toString() + ")");
return null;
}
if (responseCode == 404) {
// Authorization Error
Log.e(TAG, "Not found error in " + url + "(" + postDataBuilder.toString() + ")");
// throw new Exception("Authorization Error in " + method + "("
// + postDataBuilder.toString() + ")");
return null;
}
if ((responseCode >= 500) && (responseCode <= 504)) {
// Server Error
Log.e(TAG, "Internal server error in " + url + "(" + postDataBuilder.toString() + ")");
// throw new Exception("Internal Server Error in " + method +
// "("
// + postDataBuilder.toString() + ")");
return null;
}
in = new InputStreamReader((InputStream) conn.getContent());
buff = new BufferedReader(in);
String line;
while ((null != (line = buff.readLine())) && !"null".equals(line)) {
text.append(line + "\n");
}
buff.close();
buff = null;
in.close();
in = null;
conn.disconnect();
conn = null;
} catch (final Exception e) {
Log.e(TAG, "Exception while connecting to " + url + " with parameters: " + postDataBuilder + ", exception: " + e.toString() + ", cause: "
+ e.getCause() + ", message: " + e.getMessage());
e.printStackTrace();
return null;
} finally {
if (null != out) {
try {
out.close();
} catch (final IOException e1) {
}
out = null;
}
if (null != buff) {
try {
buff.close();
} catch (final IOException e1) {
}
buff = null;
}
if (null != in) {
try {
in.close();
} catch (final IOException e1) {
}
in = null;
}
if (null != conn) {
conn.disconnect();
conn = null;
}
}
final String temp = text.toString();
if (text.length() > 0) {
Log.i(TAG, "Success in " + url + "(" + postDataBuilder.toString() + ") = " + temp);
return temp;
}
Log.w(TAG, "Warning: " + url + "(" + postDataBuilder.toString() + "), text = " + temp);
return null;
}

Related

java.net.SocketException: Connection reset by peer. In custom twitch bot

I created custom Twitch bot with using of cavariux library. I called this methods in main class.
bot.setOauth_Key("oauth:key_Value");
bot.connect();
bot.joinChannel(channel.toString());
bot.start();
Approximately one of the 5-6 launches of the bot is accompanied by an exception
java.net.SocketException: Connection reset by peer
. The stack trace indicates that the exception starts on this line.
while ((line = this.reader.readLine( )) != null && !stopped)
in TwitchBot class in method start(). I didn't change code of this library except adding utf encoding in method connect(String ip, int port).
this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
I've tested my bot on different PCs. On some machines I don't have this issue. On some I got this exception more often.
This is code of method start() in TwitchBot class.
public final void start()
{
if (isRunning()) return;
String line = "";
stopped = false;
try {
while ((line = this.reader.readLine( )) != null && !stopped) {
if (line.toLowerCase( ).startsWith("ping")) {
LOGGER.log(Level.INFO,"> PING");
LOGGER.log(Level.INFO,"< PONG " + line.substring(5));
this.writer.write("PONG " + line.substring(5) + "\r\n");
this.writer.flush();
} else if (line.contains("PRIVMSG"))
{
String str[];
str = line.split("!");
final User msg_user = User.getUser(str[0].substring(1, str[0].length()));
str = line.split(" ");
Channel msg_channel;
msg_channel = Channel.getChannel(str[2], this);
String msg_msg = line.substring((str[0].length() + str[1].length() + str[2].length() + 4), line.length());
LOGGER.log(Level.INFO,"> " + msg_channel + " | " + msg_user + " >> " + msg_msg);
if (msg_msg.startsWith(commandTrigger))
onCommand(msg_user, msg_channel, msg_msg.substring(1));
if (msg_user.toString().equals("jtv") && msg_msg.contains("now hosting")) {
String hoster = msg_msg.split(" ")[0];
onHost(User.getUser(hoster), msg_channel);
}
onMessage(msg_user, msg_channel, msg_msg);
} else if (line.contains(" JOIN ")) {
String[] p = line.split(" ");
String[] pd = line.split("!");
if (p[1].equals("JOIN"))
userJoins(User.getUser(pd[0].substring(1)), Channel.getChannel(p[2], this));
} else if (line.contains(" PART ")) {
String[] p = line.split(" ");
String[] pd = line.split("!");
if (p[1].equals("PART"))
userParts(User.getUser(pd[0].substring(1)), Channel.getChannel(p[2], this));
} else if (line.contains(" WHISPER ")) {
String[] parts = line.split(":");
final User wsp_user = User.getUser(parts[1].split("!")[0]);
String message = parts[2];
onWhisper(wsp_user, message);
} else if (line.startsWith(":tmi.twitch.tv ROOMSTATE")) {
} else if (line.startsWith(":tmi.twitch.tv NOTICE"))
{
String[] parts = line.split(" ");
if (line.contains("This room is now in slow mode. You may send messages every"))
{
LOGGER.log(Level.INFO,"> Chat is now in slow mode. You can send messages every " + parts[15] + " sec(s)!");
} else if (line.contains("subscribers-only mode")) {
if (line.contains("This room is no longer"))
LOGGER.log(Level.INFO,"> The room is no longer Subscribers Only!");
else
LOGGER.log(Level.INFO,"> The room has been set to Subscribers Only!");
} else {
LOGGER.log(Level.INFO,line);
}
} else if (line.startsWith(":jtv MODE "))
{
String[] p = line.split(" ");
if (p[3].equals("+o")) {
LOGGER.log(Level.INFO,"> +o " + p[4]);
} else {
LOGGER.log(Level.INFO,"> -o " + p[4]);
}
} else if (line.toLowerCase().contains("disconnected"))
{
LOGGER.log(Level.INFO, line);
this.connect();
} else
{
LOGGER.log(Level.INFO,"> " + line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
This is code of method connect() in TwitchBot class.
public void connect(String ip, int port)
{
if (isRunning()) return;
try{
if (user == null || user == "")
{
LOGGER.log(Level.SEVERE, "Please select a valid Username");
System.exit(1);
return;
}
if (oauth_key == null || oauth_key == "")
{
LOGGER.log(Level.SEVERE,"Please select a valid Oauth_Key");
System.exit(2);
return;
}
#SuppressWarnings("resource")
Socket socket = new Socket(ip, port);
this.writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream(),StandardCharsets.UTF_8));
this.writer.write("PASS " + oauth_key + "\r\n");
this.writer.write("NICK " + user + "\r\n");
this.writer.write("USER " + this.getVersion() + " \r\n");
this.writer.write("CAP REQ :twitch.tv/commands \r\n");
this.writer.write("CAP REQ :twitch.tv/membership \r\n");
this.writer.flush();
String line = "";
while ((line = this.reader.readLine()) != null)
{
if (line.indexOf("004") >= 0) {
LOGGER.log(Level.INFO,"Connected >> " + user + " ~ irc.twitch.tv");
break;
}else {
LOGGER.log(Level.INFO,line);
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
Thank you for the help
This error means that the peer (i.e. the Twitch server) closes abruptly your connection. See this answer for more details.
I don't know if you can do something to fix that because it can have various external origins (peer crash...). Maybe you can wait and try to reconnect later (note that you might be blacklisted if you connect too often).

Consume Zimbra Get Calendar REST Api in Java

I get this error when I consume the REST Api of Zimbra on Android: must Athenticate java.lang.RuntimeException: Failed : HTTP error code : 401
at ZimbraREST.main(ZimbraREST.java:33). However I am absolutely sure that my login and my password are the good ones and my code was working perfectly fine yesterday, and I did not modify any important stuff linked to this code. This code should get me an xml file that I use to get sync calendar on my app. Thanks for your help. Here is my code:
#Override
protected Void doInBackground(Integer... integers) {
System.out.println("15email_adress=" + email_adress);
System.out.println("15password=" + password);
String dayStart = String.valueOf(integers[0]);
String monthStart = String.valueOf(integers[1]);
String yearStart = String.valueOf(integers[2]);
String dayEnd = String.valueOf(integers[3]);
String monthEnd = String.valueOf(integers[4]);
String yearEnd = String.valueOf(integers[5]);
String[] strings = {dayStart, monthStart, yearStart, dayEnd, monthEnd, yearEnd};
int k = 0;
for(String s: strings){
if(s.length() < 2){
strings[k] = "0" + s;
}
k++;
}
dayStart = strings[0];
monthStart = strings[1];
yearStart = strings[2];
dayEnd = strings[3];
monthEnd = strings[4];
yearEnd = strings[5];
try {
URL url = new URL("https://zmail.insa-lyon.fr/home/" + email_adress + "/Calendrier%20Cocktail?fmt=xml&start=" +
monthStart +
"/" +
dayStart +
"/" +
yearStart +
"&end=" +
monthEnd +
"/" +
dayEnd +
"/" +
yearEnd);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(email_adress, password.toCharArray());
}
});
conn.setRequestMethod("GET");
conn.setRequestProperty("--user", email_adress + ":" + password);
if (conn.getResponseCode() != 200) {
System.out.println("15erreur=" + url.toString());
System.out.println("15erreur=" + conn.getResponseMessage());
System.out.println("15erreur=" + conn.getRequestMethod());
return null;
}
System.out.println(conn.getResponseMessage());
InputStreamReader inputStreamReader = new InputStreamReader((conn.getInputStream()));
BufferedReader br = new BufferedReader(inputStreamReader);
String output;
StringBuilder xml = new StringBuilder();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
xml.append(output);
}
inputStreamReader.close();
br.close();
conn.disconnect();
System.out.println(xml);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml.toString())));
rootElement = document.getDocumentElement();
} catch (IOException | ParserConfigurationException | SAXException e) {
e.printStackTrace();
}
return null;
}
Ok so I had to authenticate the user with the code below:
// Authentication part -------------------
String userpass = email_adress + ":" + password;
conn.setRequestProperty("X-Requested-With", "Curl");
String basicAuth = "Basic " + new String(android.util.Base64.encode(userpass.getBytes(), android.util.Base64.DEFAULT));
conn.setRequestProperty("Authorization", basicAuth);
// ----------------------------------------

android - Теxtview not change instantly

I accept the array from the server, and then fill the data textview.
private class ReadMessages extends AsyncTask<Void, Void, Integer>
{
HttpURLConnection conn;
String ansver, bfr_st;
JSONArray JsonArray;
protected Integer doInBackground(Void... params) {
try {
String post_url = server_name +"/chat.php?action=select";
conn = (HttpURLConnection) new URL(post_url).openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream(); //канал
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); //буфер
StringBuilder sb = new StringBuilder(); //сборщик строки
while ((bfr_st = br.readLine()) != null) {
sb.append(bfr_st); //получили массив в виде string
}
String json_bum = sb.toString();
JsonArray = new JSONArray(json_bum); //преобразовали string обратно в массив
for (int i=0; i<JsonArray.length(); i++) {
jsonObject = JsonArray.getJSONObject(i); //вынули все обьекты
}
tv_number.setText("Номер - " + jsonObject.getInt("_id") +
"\n"
+ "Автор - " + jsonObject.getString("author") +
"\n"
+ "Адресат - " + jsonObject.getString("client") +
"\n"
+ "Время - " + jsonObject.getLong("data") +
"\n"
+ "Текст - " + jsonObject.getString("text") +
"\n");
is.close();
br.close();
} catch (Exception e) {
} finally {
conn.disconnect();
}
return null;
}
}
when I fold the application and then come back to it the text changes . but immediately when you press a button that does not happen
You can only update your GUI elements/widgets from app main thread. AsyncTask is creating seperate thread and you can't do this from method doInBackground, try use publishProgress and onProgressUpdate or do all this staff in onPostExecute
You're not allowed to update GUI on a separate thread. You should update it in the OnPostExecute within your AsyncTask. Also, you must #Override the doInBackground.
private class ReadMessages extends AsyncTask<Void, Void, Integer> {
HttpURLConnection conn;
String ansver, bfr_st;
JSONArray JsonArray;
#Override
protected Integer doInBackground(Void... params) {
try {
String post_url = server_name +"/chat.php?action=select";
conn = (HttpURLConnection) new URL(post_url).openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream(); //канал
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); //буфер
StringBuilder sb = new StringBuilder(); //сборщик строки
while ((bfr_st = br.readLine()) != null) {
sb.append(bfr_st); //получили массив в виде string
}
String json_bum = sb.toString();
JsonArray = new JSONArray(json_bum); //преобразовали string обратно в массив
for (int i=0; i<JsonArray.length(); i++) {
jsonObject = JsonArray.getJSONObject(i); //вынули все обьекты
}
is.close();
br.close();
} catch (Exception e) {
} finally {
conn.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
tv_number.setText("Номер - " + jsonObject.getInt("_id") +
"\n"
+ "Автор - " + jsonObject.getString("author") +
"\n"
+ "Адресат - " + jsonObject.getString("client") +
"\n"
+ "Время - " + jsonObject.getLong("data") +
"\n"
+ "Текст - " + jsonObject.getString("text") +
"\n");
}
Why you decided it must be immediately ? It depends on your internet speed, ping and etc. Good practice is using progressBar to show user that something is happening, not just empty screen and then textView appears after several seconds.
The line in doInbackground:
tv_number.setText("Номер - " + jsonObject.getInt("_id") +
"\n"
+ "Автор - " + jsonObject.getString("author") +
"\n"
+ "Адресат - " + jsonObject.getString("client") +
"\n"
+ "Время - " + jsonObject.getLong("data") +
"\n"
+ "Текст - " + jsonObject.getString("text") +
"\n");
actually throws an exception, but the empty catch statement prevents the app from crashing.
you can't update views from a background thread, updating UI must be on the UI thread. In case of AsyncTask you can do this in onPostExecute or onProgressUpdate methods.
change your doInBackground implementation, make it return a String:
protected String doInBackground(Void... params){
}
then in onPostExecute, update the textview
protected onPostExecute(String result){
tv_number.setText(result);
}

number of search result from Bing API

how can i access to number of search result in bing search?
i found this thread:
How to get number of search result from Bing API
in this thread i understand that i should use d->results[0]->WebTotal
but how can i use this line in java?
public static void main(String[] args) throws Exception {
//term1
String searchText = "is";
searchText = searchText.replaceAll(" ", "%20");
String accountKey="WOCKN8uXArczOkQq5phtoEc7usB0kDoPTnbqn0sKWeg";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=%27" + searchText + "%27&$top=50&$format=Atom");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
//conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
char[] buffer = new char[4096];
while ((output = br.readLine()) != null) {
sb.append(output);
//text.append(link + "\n\n\n");//Will print the google search links
//}
}
conn.disconnect();
int find = sb.indexOf("<d:Description");
int total = find + 1000;
System.out.println("Find index: " + find);
System.out.println("Total index: " + total);
sb.getChars(find+35, total, buffer, 0);
String str = new String(buffer);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
http://learn-it-stuff.blogspot.com/2012/09/using-bing-custom-search-inside-your.html
I found the answer:
public static void main(String[] args) {
String searchText = "searchtext";
searchText = searchText.replaceAll(" ", "%20");
String accountKey="key_ID";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Web%27&Query=%27" + searchText + "%27&$format=JSON");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
//write json to string sb
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
//find webtotal among output
int find= sb.indexOf("\"WebTotal\":\"");
int startindex = find + 12;
int lastindex = sb.indexOf("\",\"WebOffset\"");
System.out.println(sb.substring(startindex,lastindex));
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Paypal & Java: Not Showing order summary and failure in acknowledgement

In my paypal JSP application , when redirect to paypal account(https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-50634332TM915520D) it doesn't show account summary(As in the image). At last at success page it shows failure also.
.
setcheckout.jsp is
<body>
<%
String url = "https://api-3t.sandbox.paypal.com/nvp";
String charset = "UTF-8";
String user = "cinewo_13895465_biz_api1.gmail.com";
String pwd = "1233310405";
String signature = "AbLJtIu5Xk-EeZNM1Qxyhl8A3UcjAXCXJk7gW24OlxsLXL3ORPJX5no3";
//Get the amount here
String amount = "20";
String amt = request.getParameter("amount");
System.out.println("amt : "+amt);
if ( amt != null) {
amount = amt;
// Setting amount to session
session.setAttribute("amount", amount);
}
// Please give your ip address here not localhost
// if dont no ip addrress just take google on your sys and search what is my ip it shows give it here
String returnurl = "http://192.168.0.230:8084/Payment/sucess.jsp";
String cancelurl = "http://192.168.0.230:8084/Payment/canceled.jsp";
String query = "USER=" + user + "&PWD=" + pwd + "&SIGNATURE=" + signature + "&PAYMENTREQUEST_0_PAYMENTACTION=Sale&"
+ "PAYMENTREQUEST_0_AMT=" + amount + "&RETURNURL=" + returnurl + "&CANCELURL=" + cancelurl + "&METHOD=SetExpressCheckout"
+ "&VERSION=84.0";
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
OutputStream output = null;
try {
output = connection.getOutputStream();
output.write(query.getBytes(charset));
} finally {
if (output != null) {
try {
output.close();
} catch (IOException logOrIgnore) {
System.out.println("logOrIgnore : " + logOrIgnore);
}
}
}
InputStream resp = connection.getInputStream();
// StringBufferInputStream buf = new StringBufferInputStream(s);
InputStreamReader reader = new InputStreamReader(resp);
// Read from the input stream.
int charRead;
String outp = "";
char tmp;
while ((charRead = reader.read()) >= 0) {
System.out.print((char) charRead);
tmp = (char) charRead;
outp += Character.toString(tmp);
// out.print((char)charRead);
}
out.println("outp : " + outp);
// Close the InputStreamReader and the
// StringBufferInputStream objects.
resp.close();
reader.close();
String decoded = URLDecoder.decode(outp, charset);
//String n= URLEncoder.encode(outp, charset);
String[] params = decoded.split("&");
String[] eachpair;
HashMap<String, String> hm = new HashMap<String, String>();
for (int i = 0; i < params.length; i++) {
eachpair = params[i].split("=");
hm.put(eachpair[0], eachpair[1]);
}
String ack = "", token = "", version = "", tms = "", bld = "", corelid = "";
out.println("ACK : " + hm.get("ACK"));
ack = hm.get("ACK");
if (ack.equals("Success")) {
token = hm.get("TOKEN");
version = hm.get("VERSION");
tms = hm.get("TIMESTAMP");
bld = hm.get("BUILD");
corelid = hm.get("CORRELATIONID");
String logurl = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + token;
response.sendRedirect(logurl);
}
System.out.println("resp :" + resp);
// final String PAYPAL_URL = "https://api-3t.sandbox.paypal.com/nvp";
%>
<h1>Hello World!</h1>
</body>
and success.jsp is
<%
String user = "cinewo_13895465_biz_api1.gmail.com";
String pwd = "1325310405";
String signature = "AbLJtIu5Xk-EeZNM1Qxyhl8A3UcjAXCXJk7gW24OlxsLXL3ORPJX5no3";
String payerID = request.getParameter("PayerID");
String token = request.getParameter("token");
String amount = "25";
//Reading amount from session
String amt = session.getAttribute("amount")+"";
if(amt!=""){
amount=amt;
}
String version = request.getParameter("VERSION");
String build = request.getParameter("BUILD");
String charset = "UTF-8";
token = URLEncoder.encode(token, charset);
payerID = URLEncoder.encode(payerID, charset);
String query = "USER=" + user + "&PWD=" + pwd + "&SIGNATURE=" + signature + "&PAYMENTACTION=Sale&"
+ "PAYERID=" + payerID + "&TOKEN=" + token + "&AMT=" + amount + "&METHOD=DoExpressCheckoutPayment"
+ "&VERSION=84.0";
String url = "https://api-3t.sandbox.paypal.com/nvp";
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
OutputStream output = null;
try {
output = connection.getOutputStream();
output.write(query.getBytes(charset));
} finally {
if (output != null) {
try {
output.close();
} catch (IOException logOrIgnore) {
System.out.println("logOrIgnore : " + logOrIgnore);
}
}
}
InputStream resp = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(resp);
// Read from the input stream.
int charRead;
String outp = "";
char tmp;
while ((charRead = reader.read()) >= 0) {
System.out.print((char) charRead);
tmp = (char) charRead;
outp += Character.toString(tmp);
// out.print((char)charRead);
}
String decoded = URLDecoder.decode(outp, charset);
//out.println("decoded : " + decoded);
String[] params = decoded.split("&");
String[] eachpair;
HashMap<String, String> hm = new HashMap<String, String>();
for (int i = 0; i < params.length; i++) {
eachpair = params[i].split("=");
hm.put(eachpair[0], eachpair[1]);
}
String ack = "", corelid = "", tms = "", bld = "";
out.println("ACK : " + hm.get("ACK"));
ack = hm.get("ACK");
if (ack.equals("Success")) {
token = hm.get("TOKEN");
version = hm.get("VERSION");
tms = hm.get("TIMESTAMP");
bld = hm.get("BUILD");
corelid = hm.get("CORRELATIONID");
out.println("token : " + token);
out.println("version : " + version);
out.println("tms : " + tms);
out.println("bld : " + bld);
out.println("corelid : " + corelid);
} else {
out.println("Sorry try again later");
}
// Close the InputStreamReader and the
// StringBufferInputStream objects.
resp.close();
reader.close();
%>
<h1>Hello Sucess</h1>
</body>
To show order summery change https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-50634332TM915520D to https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + token+"&useraction=commit"

Categories

Resources