Consume Zimbra Get Calendar REST Api in Java - 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);
// ----------------------------------------

Related

Java HttpURLConnection Digest Authentication getting 401

I am getting a 401 on the second request to a 3rd party URL, even though I followed the digest auth guidelines for creating the second request. It is pretty simplistic code because I am not very well versed in this but I think it is close. We are stuck using Java 1.7. I tried using HTTPClient but kept getting connection reset. I am getting further with HTTPUrlConnection (now getting the 401 and the WWW-Authenticate header) but I can't get past the second request.
\\Building body of request
String bodydata = URLEncoder.encode("apikey", "UTF-8") + "=" + URLEncoder.encode("somekey", "UTF-8");
bodydata += "&" + URLEncoder.encode("format", "UTF-8") + "=" + URLEncoder.encode("JSON", "UTF-8");
//print out the JSON search request
data.addToLog("JSONSearchRequest",bodydata.toString());
try {
URL myurl = new URL(null, baseurl , new sun.net.www.protocol.https.Handler() );
SSLContext sc = SSLContext.getInstance("TLSv1.2"); //$NON-NLS-1$
sc.init(null, null, new java.security.SecureRandom());
HttpsURLConnection con = (HttpsURLConnection )myurl.openConnection();
con.setSSLSocketFactory(sc.getSocketFactory());
//con.setSSLSocketFactory(new TSLSocketConnectionFactory());
con.setRequestProperty("username", userName);
con.setRequestProperty("nonce", "12345" ); //nonce64
con.setRequestProperty("realm", "some realm.");
con.setRequestProperty("algorithm", "MD5");
con.setRequestProperty("qop", "auth");
con.setRequestProperty("nc", "1");
con.setRequestProperty("uri", "/studio_instance/studio-api/v1/auth/get-token/");
con.setRequestProperty("Cookie", "some cookie value");
con.setRequestMethod(method);
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
out.write(bodydata);
out.flush();
out.close();
if (con != null){
con.setReadTimeout(60 * 1000);
data.addToLog("Response Code= ", con.getResponseCode() +": "+ con.getResponseMessage());
}
for (String header : con.getHeaderFields().keySet()) {
if (header != null) {
for (String value : con.getHeaderFields().get(header)) {
//System.out.println(header + ":" + value);
if (auth == null) {
data.addToLog("WWWauthenticateHeader :: " ,"is blank");
} else {
//for (String header : auth) {
String[] assetClasses = auth.split(","); // print [Equity, Gold, FixedIncome, Derivatives] System.out.println(Arrays.toString(assetClasses));
realm2=assetClasses[0]; realm2=realm2.substring(realm2.indexOf("=") + 1); realm2=realm2.replace("\"", ""); qop2=assetClasses[1]; qop2=qop2.substring(qop2.indexOf("=") + 1); qop2=qop2.replace("\"", ""); nonce2=assetClasses[3]; nonce2=nonce2.substring(nonce2.indexOf("=") + 1); nonce2=nonce2.replace("\"", ""); opaque2=assetClasses[4]; opaque2=opaque2.substring(opaque2.indexOf("=") + 1); opaque2=opaque2.replace("\"", "");
}
}
}
}
// the first call ALWAYS fails with a 401
String bodydata2 = URLEncoder.encode("apikey", "UTF-8") + "=" + URLEncoder.encode("someapikey", "UTF-8");
bodydata2 += "&" + URLEncoder.encode("format", "UTF-8") + "=" + URLEncoder.encode("JSON", "UTF-8");
//print out the JSON search request
try {
URL myurl2 = new URL(null, baseurl , new sun.net.www.protocol.https.Handler() );
SSLContext sc2 = SSLContext.getInstance("TLSv1.2"); //$NON-NLS-1$
data.addToLog("URL2",myurl2.toString());
sc2.init(null, null, new java.security.SecureRandom());
HttpsURLConnection con2 = (HttpsURLConnection )myurl2.openConnection();
con2.setSSLSocketFactory(sc2.getSocketFactory());
MessageDigest md5 = null;
try{
md5 = MessageDigest.getInstance("MD5");
}
catch(NoSuchAlgorithmException e){
return null;
}
StringBuilder sbha1 = new StringBuilder();
sbha1.append(userName).append(":").append(realm2).append(":").append(password);
String ha1string = sbha1.toString();
md5.reset();
md5.update(ha1string.getBytes("ISO-8859-1"));
byte[] ha1bytes = md5.digest();
ha1 = Hex.encodeHexString(ha1bytes);
StringBuilder sbha2 = new StringBuilder();
sbha2.append("GET").append(":").append("path");
String ha2string = sbha2.toString();
md5.reset();
md5.update(ha2string.getBytes("ISO-8859-1"));
byte[] ha2bytes = md5.digest();
ha2 = Hex.encodeHexString(ha2bytes);
StringBuilder sbha3 = new StringBuilder();
sbha3.append(ha1).append(":").append(nonce2).append(":").append(ha2);
String ha3string = sbha3.toString();
md5.reset();
md5.update(ha3string.getBytes("ISO-8859-1"));
byte[] ha3bytes = md5.digest();
ha3 = Hex.encodeHexString(ha3bytes);
con2.setRequestProperty("Content-Type", "application/json;charset=utf-8");
StringBuilder sb2 = new StringBuilder(128);
sb2.append("Digest ");
sb2.append("username").append("=\"").append(userName).append("\", ");
sb2.append("realm").append("=\"").append(realm2).append("\", ");
sb2.append("nonce").append("=\"").append(nonce2).append("\", ");
sb2.append("uri").append("=\"").append(path).append("\", ");
sb2.append("qop").append("=\"").append(qop2).append("\", ");
sb2.append("nc").append("=\"").append("1").append("\", ");
sb2.append("cnonce").append("=\"").append("12345").append("\"");
sb2.append("response").append("=\"").append(ha3).append("\"");
sb2.append("opaque").append("=\"").append(opaque2).append("\", ");
//sb2.append("algorithm").append("=\"").append("MD5").append("\"");
digestAuthStr = sb2.toString();
con2.setRequestProperty("Authorization", digestAuthStr);
con2.setRequestMethod("GET");
con2.setDoOutput(true);
OutputStreamWriter out2 = new OutputStreamWriter(con2.getOutputStream());
out2.write(bodydata2);
out2.flush();
out2.close();
if (con2 != null){
con2.setReadTimeout(60 * 1000);
}

Get Authentication error when put object to Azure storage

I am using java to make a REST Api call to Azure, put an object to its storage.
I did this successfully last week but now its now working for some reasons.
The error message is as below:
<?xml version="1.0" encoding="utf-8" ?>
<Error>
<Code>AuthenticationFailed</Code>
<Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:a15f2626-0001-004f-778c-f34383000000 Time:2017-07-02T23:43:20.2826278Z</Message>
<AuthenticationErrorDetail>The Date header in the request is incorrect.</AuthenticationErrorDetail>
</Error>
I don't think this is caused by the incorrect time stamp because the "Date" field and the response time are within 15 minutes. The "Date" field in the header is Sun, 2 Jul 2017 23:38:04 GMT
Here are my java code to generate the token and send the request.
public void putObject(String blobName) {
try {
URL restServiceURL = new URL(getCallAddress() + "/" + blobName);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
Calendar cd = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String date = sdf.format(cd.getTime());
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
try {
httpConnection.setRequestMethod("PUT");
} catch (ProtocolException e) {
e.printStackTrace();
}
httpConnection.setFixedLengthStreamingMode(getFile().length()); //set output size to avoid out of memory error
try {
String token = createToken(blobName, date);
httpURLConnection.setRequestProperty("Authorization", "SharedKey " + Azure_AccountName + ":" + token);
} catch (Exception e) {
log.error("Cannot get token");
e.printStackTrace();
}
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(getFile().length()));
httpURLConnection.setRequestProperty("x-ms-blob-type", "BlockBlob");
httpURLConnection.setRequestProperty("x-ms-version", "2015-12-11");
httpURLConnection.setRequestProperty("x-ms-date",date);
} catch (IOException e) {
log.error(e);
e.printStackTrace();
}
FileInputStream inputStream = new FileInputStream(getFile());
try {
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
OutputStream out = httpConnection.getOutputStream();
out.write(buffer);
out.flush();
out.close();
int code = httpConnection.getResponseCode();
if (code != 201 && code != 200) {
log.error(code + httpConnection.getResponseMessage());
throw new UnsupportedOperationException("Put object failed");
}
httpConnection.disconnect();
} catch (Exception e) {
log.error(e);
e.printStackTrace();
} finally {
IOUtils.closeQuietly(inputStream);
}
}
private String createToken(String blobName, String date) throws InvalidKeyException, NoSuchAlgorithmException,
UnsupportedEncodingException {
String signature = "PUT\n\n\n" + getFile().length() + "\n\n\n\n\n\n\n\n\nx-ms-blob-type:BlockBlob\nx-ms-date:" + date +
"\nx-ms-version:2015-12-11\n" + "/" + Azure_AccountName + "/" + Azure_BucketName + "/" + blobName;
SecretKey secreteKey = new SecretKeySpec(Base64.decode(KEY), "HmacSHA256");
Mac sha256HMAC = Mac.getInstance(secreteKey.getAlgorithm());
sha256HMAC.init(secreteKey);
byte[] digest = sha256HMAC.doFinal(signature.getBytes("UTF8"));
return new String(Base64.encode(digest));
}
You could refer to the code below if you haven't solved this Authentication error:
public class PutTest {
private static final String account = <your account name>;
private static final String key = <your account key>;
public static void main(String args[]) throws Exception {
File file = new File(<your file path>);
FileInputStream inputStream = new FileInputStream(<your file path>);
String urlString = "https://" + account + ".blob.core.windows.net/<your container>/<your file name e.g:test.txt>";
HttpURLConnection connection = (HttpURLConnection) (new URL(urlString)).openConnection();
getFileRequest(connection, account, key, file.length());
// connection.connect();
connection.setDoInput(true);
connection.setDoOutput(true);
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
OutputStream out = connection.getOutputStream();
out.write(buffer);
out.flush();
out.close();
System.out.println("Response message : " + connection.getResponseMessage());
System.out.println("Response code : " + connection.getResponseCode());
BufferedReader br = null;
if (connection.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
public static void getFileRequest(HttpURLConnection request, String account, String key, long length)
throws Exception {
SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String date = fmt.format(Calendar.getInstance().getTime()) + " GMT";
String stringToSign = "PUT\n" + "\n" // content encoding
+ "\n" // content language
+length+"\n"// content length
+ "\n" // content md5
+"\n" // content type
+ "\n" // date
+ "\n" // if modified since
+ "\n" // if match
+ "\n" // if none match
+ "\n" // if unmodified since
+ "\n" // range
+ "x-ms-blob-type:BlockBlob" + "\n"
+ "x-ms-date:" + date + "\n"
+ "x-ms-version:2015-02-21"+"\n" // headers
+ "/" + account + request.getURL().getPath(); // resources
System.out.println("stringToSign : " + stringToSign);
String auth = getAuthenticationString(stringToSign);
request.setRequestMethod("PUT");
request.setRequestProperty("x-ms-blob-type", "BlockBlob");
request.setRequestProperty("x-ms-date", date);
request.setRequestProperty("x-ms-version", "2015-02-21");
request.setRequestProperty("Authorization", auth);
request.setRequestProperty("Content-Length", String.valueOf(length));
}
private static String getAuthenticationString(String stringToSign) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(Base64.decode(key), "HmacSHA256"));
String authKey = new String(Base64.encode(mac.doFinal(stringToSign.getBytes("UTF-8"))));
String auth = "SharedKey " + account + ":" + authKey;
return auth;
}
}
Hope it helps.

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

Sending POST from Android Application

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

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