Google Distance Matrix not getting distance - java

I have roughly tried to parse the JSON from Google Distance Matrix API, but it is not showing the distance.
My GPS location is not 0,0 that I'm sure of.
String distance = getMatrix(latitude,longitude);
My code for the function is:
private String getMatrix(double lat , double lang){
JSONObject jObj;
String getdistance = "";
String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ Double.toString(my_lat) + ","
+ Double.toString(my_lang)
+ "&destinations="+ Double.toString(lat) + ","
+ Double.toString(lang)
+ "&mode=walking&sensor=false";
String data = "";
InputStream reader = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
reader = urlConnection.getInputStream();
int bRead = -1;
byte[] buffer = new byte[1024];
do {
bRead = reader.read(buffer, 0, 1024);
if (bRead == -1) {
break;
}
data += new String(buffer, 0, bRead);
} while (true);
urlConnection.disconnect();
} catch(Exception e) {
} finally {
}
try {
jObj = new JSONObject(data);
JSONArray rowsArray = jObj.getJSONArray("rows");
JSONObject rows = rowsArray.getJSONObject(0);
JSONArray elementsArray = rows.getJSONArray("elements");
JSONObject newDisTimeOb = elementsArray.getJSONObject(0);
JSONObject distOb = newDisTimeOb.getJSONObject("distance");
getdistance = distOb.optString("text").toString();
} catch (JSONException e) {
e.printStackTrace();
}
return getdistance;
}

First, check if you've correctly build the url string in the code:
String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ Double.toString(my_lat) + ","
+ Double.toString(my_lang)
+ "&destinations="+ Double.toString(lat) + ","
+ Double.toString(lang)
+ "&mode=walking&sensor=false";
// Line to check if url code is right
Log.d("APP", "strUrl = " + strUrl);
Then check your following code, whether it really produce the data:
reader = urlConnection.getInputStream();
int bRead = -1;
byte[] buffer = new byte[1024];
do {
bRead = reader.read(buffer, 0, 1024);
if (bRead == -1) {
break;
}
data += new String(buffer, 0, bRead);
} while (true);
My suggestion is to use BufferedReader instead reading the response byte per byte.
Then change:
getdistance = distOb.optString("text").toString();
to
getdistance = distOb.getString("text");
Because you don't need to convert to string again here.
I've search Client Libraries for Google Maps Web Services and found DistanceMatrixApi.java. Maybe we can use it, but I can't assure of it.

Related

Fetching array from json not working

Currently I am working with a project where I need to get some data from remote server as JSON then need to extract array. Here I am getting data successfully, But problems are near while loop.
I am getting data from remote server successfully.
For example my remote url giving output as:
{"id": "1","amount": "1000","course_code": "BASIC","course": "Basic Course","content": "Sample","thumb": "sample.png"},
{"id": "2","amount": "2000","course_code": "ADVANCED","course": "Advanced Course","content": "Sample","thumb": "sample.png"}`
Code
try {
ur = "http://localhost/getsample.php";
URL url = new URL(ur);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line="";
while (line !=null){
line = bufferedReader.readLine();
data = data+line;
}
data = data.replace("null", "");
JSONArray JA = new JSONArray(data);
for (int i=0;i<JA.length();i++){
JSONObject JO = (JSONObject) JA.get(i);
idArray = idArray + JO.get("id") + ",";
amountArray = amountArray + JO.get("amount") + ",";
course_codeArray = course_codeArray + JO.get("course_code") + ",";
courseArray = courseArray + JO.get("course") + ",";
contentArray = contentArray + JO.get("content") + ",";
thumbArray = thumbArray + JO.get("thumb") + ",";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
The data you get from the server are at JSON format but they are not Array . this is an object ,
{"id": "1","amount": "1000","course_code": "BASIC","course": "Basic Course","content": "Sample","thumb": "sample.png"},{"id": "2","amount": "2000","course_code": "ADVANCED","course": "Advanced Course","content": "Sample","thumb": "sample.png"}
So you have to loop inside the json object like
for (var key in jsonResponse) {
if (jsonResponse.hasOwnProperty(key)) {
console.log(key + " -> " + jsonResponse[key]);
}
}
EDIT : If you have multiple Objects inside an object you have to loop inside them ( external for) like for(var i in JsonObject)
Your Code is should be like According to your current Response
try{
JSONObject jso = new JSONObject(data);
amountArray =jsonObject.getString("amount");
course_codeArray =jsonObject.getString("yourNextKey");
courseArray = jsonObject.getString("yourNextKey");
contentArray = jsonObject.getString("yourNextKey");
thumbArray = jsonObject.getString("yourNextKey");
}
catch (JSONException e) {
e.printStackTrace();
}

multiple upload images file using httpurlconnection

I have many images in a folder, and I want to upload this files, in that folder, to a php server, in java using httpurlconnection.
Until now, I made it but just with one photo, like the code I show you down.
public class SendImage {
private final String CrLf = "\r\n";
public static void main(String[] args) {
SendImage image = new SendImage();
image.httpConn();
}
private void httpConn(){
URLConnection lig = null;
OutputStream os = null;
InputStream is = null;
try{
String urlParameters = "subPasta=sandro&nomepc=Sandro-PC&printPasta=Printscreens";;
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
URL url = new URL("http://192.168.0.105/dashboard3/uploadImg.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
conn.setUseCaches(false);
System.out.println("url: "+ url);
lig = url.openConnection();
lig.setDoOutput(true);
FileInputStream imgIs = new FileInputStream(new File("C:\\Users\\Sandro\\workspace\\testeLogin\\screenshot\\2017_3_16_3_59.png"));
byte[] imgData = new byte[imgIs.available()];
imgIs.read(imgData);
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"image.png\"" + CrLf;
message1 += "Content-Type: image/jpeg" + CrLf;
message1 += CrLf;
// the image is sent between the messages in the multipart message.
String message2 = "";
message2 += CrLf + "-----------------------------4664151417711--" + CrLf;
lig.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
// might not need to specify the content-length when sending chunked
// data.
lig.setRequestProperty("Content-Length", String.valueOf((message1
.length() + message2.length() + imgData.length)));
System.out.println("open os");
os = lig.getOutputStream();
System.out.println(message1);
os.write(message1.getBytes());
// SEND THE IMAGE
int index = 0;
int size = 1024;
do {
System.out.println("write:" + index);
if ((index + size) > imgData.length) {
size = imgData.length - index;
}
os.write(imgData, index, size);
index += size;
} while (index < imgData.length);
System.out.println("written:" + index);
System.out.println(message2);
os.write(message2.getBytes());
os.flush();
System.out.println("open is");
is = lig.getInputStream();
char buff = 512;
int len;
byte[] data = new byte[buff];
do {
System.out.println("READ");
len = is.read(data);
if (len > 0) {
System.out.println(new String(data, 0, len));
}
} while (len > 0);
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}finally {
System.out.println("Close connection");
try {
os.close();
} catch (Exception e) {
}
try {
is.close();
} catch (Exception e) {
}
try {
} catch (Exception e) {
}
}
}
}
But I want send all photos in that folder
if you can, show me the code in php too please.

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"

How to send an audio file to server in android?

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.

Sockets: Simple POST request not working

I am trying to make a post request on this page http://www2.gcitrading.com/quotes/converter.asp,
but its not working..I still get the same page after my post request (without the result).
When I use the browser, after I click convert the page turns to http://www2.gcitrading.com/quotes/converter.asp?lang= Im really confused with this one. How can I make this work?
Here is my code:
public static void main(String[] args) {
Socket sock = new Socket();
InputStream in;
OutputStream out;
byte[] readBuffer = new byte[4096];
String res = "";
try {
sock.connect(new InetSocketAddress("www2.gcitrading.com", 80));
in = sock.getInputStream();
out = sock.getOutputStream();
out.write(new String("GET /quotes/converter.asp HTTP/1.1\r\n").getBytes());
out.write(new String("Host: www2.gcitrading.com\r\n\r\n").getBytes());
while(true) {
int readSize = in.read(readBuffer);
if(readSize < 1)
break;
res += new String(readBuffer, 0, readSize);
if(res.contains("</html>"))
break;
}
String cookie = res.substring(res.indexOf("kie:") + 5,res.indexOf("path=/")+6);
System.out.println("SHow cookie - " + cookie);
String convert_this = URLEncoder.encode("form_amount=1&form_from_currency=DZD&form_to_currency=USD", "UTF-8");
out.write(new String("POST /quotes/converter.asp?lang= HTTP/1.1\r\n").getBytes());
out.write(new String("Host: www2.gcitrading.com\r\n").getBytes());
out.write(new String("Content-Length: " + convert_this.length() + "\r\n").getBytes());
out.write(new String("Content-Type: application/x-www-form-urlencoded\r\n").getBytes());
out.write(new String("Cookie: " + cookie +"\r\n").getBytes());
out.write(new String("\r\n").getBytes());
out.write(convert_this.getBytes());
readBuffer = new byte[4096];
res = "";
while(true) {
int readSize = in.read(readBuffer);
if(readSize < 1)
break;
res += new String(readBuffer, 0, readSize);
if(res.contains("</html>"))
break;
}
System.out.println(res);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thanks. Btw, I need to achieve this using c/c++ sockets, but I tested it using java first.
I try this it's work
String convert_this = URLEncoder.encode("form_amount", "UTF-8")+ "=" + URLEncoder.encode("1", "UTF-8");
convert_this += "&" + URLEncoder.encode("form_from_currency", "UTF-8")+ "=" + URLEncoder.encode("DZD", "UTF-8");
convert_this += "&" + URLEncoder.encode("form_to_currency", "UTF-8")+ "=" + URLEncoder.encode("USD", "UTF-8");
Try something like this:
DataOutputStream dataOut = new DataOutputStream(sock.getOutputStream());
dataOut.writeUTF("[Your String here]");
Also, you should be using the higher-level URL, not sockets.
It's solved. I used Charles, it's a web debugging tool, and found out that my post request is lacking. I simply added in my post request : convert_it=true

Categories

Resources