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);
}
Related
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);
// ----------------------------------------
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.
I'm essentially trying to mimic what's been done here through the Android app but for some reason data doesn't get returned as soon as it attempts to post data (it returns fine when I delete the writer.write(finalResult) line).
All I want right now is to be able to search for a user's data once I've sent the username.
Here's my code below:
try {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("Content-length", "0");
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.setDoInput(true);
c.setDoOutput(true);
//Attempting to send data!
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", paramValue));
OutputStream os = c.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
String finalResult = getQuery(params);
Log.d("params", finalResult);
writer.write(finalResult);
writer.close();
os.close();
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
result = sb.toString();
}
} catch (MalformedURLException ex) {
Log.e("log_tag", "Error converting result ");
} catch (IOException ex) {
Log.e("log_tag", "Error in http connection ");
}
//json code!
//parse json data
try{
JSONArray jArray = new JSONArray(result);
//for each object in our json array
for(int i =0; i < jArray.length(); i++){
JSONObject json_data =jArray.getJSONObject(i);
String address = "";
//Checks for missing data in address - Need a class for all fields
if (json_data.isNull("address")){
address = "N/A";
}
else
{
address = json_data.getString("address");;
}
//read one line of the response
myListView.setText("Username: "+json_data.getString("username")
+" / " + "Name: " + json_data.getString("name")
+" / " + "E-mail: " + json_data.getString("email")
+" / " + "Address: " + address);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data"+e.toString());
}
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
And here is my php script:
<?php
$searchuser = $_GET["username"];
$databasehost = databasehost;
$databasename = database;
$databaseusername = username;
$databasepassword = password;
$con = mysql_connect($databasehost, $databaseusername, $databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT * FROM testusers";
$sth = mysql_query($query);
if (mysql_errno()) {
header("HTTP/1.1 500 Internal Server Error");
echo $query."\n";
echo mysql_error();
}
else
{
$rows = array();
while ($r = mysql_fetch_assoc($sth)){
$rows[] = $r;
}
print json_encode($rows);
}
?>
Since you set the header Content-Length to be 0, the server doesn't even read your content... So anything you send isn't received. You should set Content-Length to finalResult.length().
remove this,
c.setRequestProperty("Content-length", "0");
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"
public static String fileUploadFromPath(String url, String path) throws Throwable {
System.out.println("IN fileUploadFromPath ");
String responseData = "";
String NL = System.getProperty("line.separator");
try {
System.out.println("url ************ " + url);
File file = new File(path);
System.out.println("file ************ " + file.getAbsolutePath()
+ " : " + file.exists());
StringBuilder text = new StringBuilder();
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append(NL);
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
// System.out.println("postRequest ************ " +
// postRequest);
MultipartEntity multipartContent = new MultipartEntity();
ByteArrayBody key = new ByteArrayBody(text.toString()
.getBytes(), AgricultureUtils.getInstance()
.getTimeStamp() + ".3gp");
multipartContent.addPart(AgricultureUtils.getInstance()
.getTimeStamp() + ".3gp", key);
postRequest.setEntity(multipartContent);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader in = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String content = "";
while ((content = in.readLine()) != null) {
sb.append(content + NL);
}
in.close();
/*
* File myDir = new File(Constants.dirctory); if
* (!myDir.exists()) { myDir.mkdirs(); } File myFile = new
* File(myDir, fileName); FileOutputStream mFileOutStream = new
* FileOutputStream(myFile);
* mFileOutStream.write(sb.toString().getBytes());
* mFileOutStream.flush(); mFileOutStream.close();
*/
System.out.println("response " + sb);
}
} catch (Throwable e) {
System.out.println("Exception In Webservice ----- " + e);
throw e;
}
return responseData;
}
I want to upload an audio file into server.
I am able upload audio file to server through above code but the file is not working(not playing in system). If u have any idea please help me.
You should be using neither FileReader nor StringBuilder here as it treats the data as characters (encoded according to the default system character set). Really, you should not be using a Reader at all. Binary data should be handled via InputStream, e.g.
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try (final InputStream in = new FileInputStream(file)) {
final byte[] buf = new byte[2048];
int n;
while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
}
final byte[] data = out.toByteArray();
Did you check checksum on server? Is it arriving unmodified?
If not, try other method to post files. This one helped me a lot:
/**
* Post request (upload files)
* #param sUrl
* #param params Form data
* #param files
* #return
*/
public static HttpData post(String sUrl, Hashtable<String, String> params, ArrayList<File> files) {
HttpData ret = new HttpData();
try {
String boundary = "*****************************************";
String newLine = "rn";
int bytesAvailable;
int bufferSize;
int maxBufferSize = 4096;
int bytesRead;
URL url = new URL(sUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream(con.getOutputStream());
//dos.writeChars(params);
//upload files
for (int i=0; i<files.size(); i++) {
Log.i("HREQ", i+"");
FileInputStream fis = new FileInputStream(files.get(i));
dos.writeBytes("--" + boundary + newLine);
dos.writeBytes("Content-Disposition: form-data; "
+ "name="file_"+i+"";filename=""
+ files.get(i).getPath() +""" + newLine + newLine);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
bytesRead = fis.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fis.read(buffer, 0, bufferSize);
}
dos.writeBytes(newLine);
dos.writeBytes("--" + boundary + "--" + newLine);
fis.close();
}
// Now write the data
Enumeration keys = params.keys();
String key, val;
while (keys.hasMoreElements()) {
key = keys.nextElement().toString();
val = params.get(key);
dos.writeBytes("--" + boundary + newLine);
dos.writeBytes("Content-Disposition: form-data;name=""
+ key+""" + newLine + newLine + val);
dos.writeBytes(newLine);
dos.writeBytes("--" + boundary + "--" + newLine);
}
dos.flush();
BufferedReader rd = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
ret.content += line + "rn";
}
//get headers
Map<String, List<String>> headers = con.getHeaderFields();
Set<Entry<String, List<String>>> hKeys = headers.entrySet();
for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) {
Entry<String, List<String>> m = i.next();
Log.w("HEADER_KEY", m.getKey() + "");
ret.headers.put(m.getKey(), m.getValue().toString());
if (m.getKey().equals("set-cookie"))
ret.cookies.put(m.getKey(), m.getValue().toString());
}
dos.close();
rd.close();
} catch (MalformedURLException me) {
} catch (IOException ie) {
} catch (Exception e) {
Log.e("HREQ", "Exception: "+e.toString());
}
return ret;
}
This is taken from:
http://moazzam-khan.com/blog/?p=490
Check link for dependencies and usage.