I need to search Goolge Places Pages by long/lat for any banks in the area of 20m.
This Google Places Doc describes how to do it with JavaScript. They are using a google.maps.LatLng Object that i don't have in Java.
Does anyone now how to call the Service?
Maybe there is also an Java API for Goolge Places?
Best Regards,
Christian.
Edit 1:
I found someone constructing the url like this:
String url = baseUrl + "location=" + lat + "," + lon + "&" +
"radius=" + searchRadius + "&" + types + "&" + "sensor=true" +
"&" + "key=" + googleAPIKey;
Answer: Edit 2:
I because of the post above i found out how to do it. This is a example how to send the request:
public class GooglePlacesClient
{
private static final String GOOGLE_API_KEY = "***";
private final HttpClient client = new DefaultHttpClient();
public static void main(final String[] args) throws ParseException, IOException, URISyntaxException
{
new GooglePlacesClient().performSearch("establishment", 8.6668310, 50.1093060);
}
public void performSearch(final String types, final double lon, final double lat) throws ParseException, IOException, URISyntaxException
{
final URIBuilder builder = new URIBuilder().setScheme("https").setHost("maps.googleapis.com").setPath("/maps/api/place/search/json");
builder.addParameter("location", lat + "," + lon);
builder.addParameter("radius", "5");
builder.addParameter("types", types);
builder.addParameter("sensor", "true");
builder.addParameter("key", GooglePlacesClient.GOOGLE_API_KEY);
final HttpUriRequest request = new HttpGet(builder.build());
final HttpResponse execute = this.client.execute(request);
final String response = EntityUtils.toString(execute.getEntity());
System.out.println(response);
}
}
Here's a more complete example (includes JSON parsing and some exception handling) for Places API search, autocomplete, and details. It was written for Android, but can be easily ported for non-Android use (need to include org.json libs and use different logging). The Place class is a simple value object.
package com.example.google.places;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
/**
* #author saxman
*/
public class PlacesService {
private static final String LOG_TAG = "ExampleApp";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String TYPE_DETAILS = "/details";
private static final String TYPE_SEARCH = "/search";
private static final String OUT_JSON = "/json";
// KEY!
private static final String API_KEY = "YOUR KEY";
public static ArrayList<Place> autocomplete(String input) {
ArrayList<Place> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE);
sb.append(TYPE_AUTOCOMPLETE);
sb.append(OUT_JSON);
sb.append("?sensor=false");
sb.append("&key=" + API_KEY);
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList<Place>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
Place place = new Place();
place.reference = predsJsonArray.getJSONObject(i).getString("reference");
place.name = predsJsonArray.getJSONObject(i).getString("description");
resultList.add(place);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON results", e);
}
return resultList;
}
public static ArrayList<Place> search(String keyword, double lat, double lng, int radius) {
ArrayList<Place> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE);
sb.append(TYPE_SEARCH);
sb.append(OUT_JSON);
sb.append("?sensor=false");
sb.append("&key=" + API_KEY);
sb.append("&keyword=" + URLEncoder.encode(keyword, "utf8"));
sb.append("&location=" + String.valueOf(lat) + "," + String.valueOf(lng));
sb.append("&radius=" + String.valueOf(radius));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("results");
// Extract the Place descriptions from the results
resultList = new ArrayList<Place>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
Place place = new Place();
place.reference = predsJsonArray.getJSONObject(i).getString("reference");
place.name = predsJsonArray.getJSONObject(i).getString("name");
resultList.add(place);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON results", e);
}
return resultList;
}
public static Place details(String reference) {
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE);
sb.append(TYPE_DETAILS);
sb.append(OUT_JSON);
sb.append("?sensor=false");
sb.append("&key=" + API_KEY);
sb.append("&reference=" + URLEncoder.encode(reference, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return null;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
Place place = null;
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString()).getJSONObject("result");
place = new Place();
place.icon = jsonObj.getString("icon");
place.name = jsonObj.getString("name");
place.formatted_address = jsonObj.getString("formatted_address");
if (jsonObj.has("formatted_phone_number")) {
place.formatted_phone_number = jsonObj.getString("formatted_phone_number");
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON results", e);
}
return place;
}
}
A Java library for working with the Google Places API is available on GitHub and in Maven Central (disclosure: I'm the developer.) Getting a list of places (or details, photo, etc.) can be done in one or two lines. See the project page for examples and set up details.
https://github.com/pushbit/sprockets
There doesn't exist any official Java library available for Google Places API. However, there are several projects hosted on Github. Another one is this:
Google Places API Java Library on Github
Related
I want to get the youtube video title from a url so I found this code below (IOUtils) is depreciated any other way to do this
public class SimpleYouTubeHelper {
public static String getTitleQuietly(String youtubeUrl) {
try {
if (youtubeUrl != null) {
URL embededURL = new URL("http://www.youtube.com/oembed?url=" +
youtubeUrl + "&format=json"
);
return new JSONObject(IOUtils.toString(embededURL)).getString("title");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
second way i tried
class getYoutubeJSON extends Thread {
String data = " ";
#Override
public void run() {
try {
URL url = new URL("http://www.youtube.com/oembed?url="+" https://www.youtube.com/watch?v=a4NT5iBFuZs&ab_channel=FilipVujovic"
+ "&format=json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null){
data =data + line;
}
if(!data.isEmpty()){
JSONObject jsonObject = new JSONObject(data);
// JSONArray users = jsonObject.getJSONArray("author_name");
Log.d("RT " , jsonObject.toString());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This code gets a an error Cleartext HTTP traffic to www.youtube.com not permitted
so I found this answer Android 8: Cleartext HTTP traffic not permitted but I am still getting some error I don't understand.
I solved this problem by using the volley library.
My requested url was:
String Video_id = "jhjgN2d7yok";
String url = "https://www.youtube.com/oembed?url=youtube.com/watch?v=" +Video_id+ "&format=json";
I have written the following code to get the JSON response from the url which has authentication. Further,this response is in the format of the JSON array. Response is kind of big so I have attached JSON response in the following link:
https://drive.google.com/file/d/1-gSM1CXQlB7eJQXXsY8_G3koJWuyZB8S/view?usp=sharing
I want to fetch the user id and their role in the form of JSON object. However I'm facing this error.Can anybody help me what went wrong and could you suggest any modification in the code?
package url_request;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONParing {
private static HttpURLConnection connection;
public static void main(String args[]) {
String usernameColonPassword = "uname:pass";
String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());
BufferedReader reader;
String line;
StringBuffer responseContent = new StringBuffer();
try {
URL url = new URL("https://ucf6-zfon-fa-ext.oracledemos.com/hcmRestApi/scim/Users");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int status = connection.getResponseCode();
// for testing the connection
// System.out.println(status);
if (status > 299) {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
} else {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
}
// System.out.println(responseContent.toString());
parse(responseContent.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
} finally {
connection.disconnect();
}
}
public static String parse(String responseBody) {
JSONArray albums;
try {
albums = new JSONArray(responseBody);
for (int i = 0; i < albums.length(); i ++) {
JSONObject album = albums.getJSONObject(i);
int id = album.getInt("id");
int role = album.getInt("roles");
System.out.println(id + " " + role);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
In the uname and pass fields, I will add the credential of the URL.
This code works for your example, althought I had to change some types, there were problems with casting
public static Map<String, Set<String>> parse(String responseBody) {
JSONObject resourcesNode = new JSONObject(responseBody); // incoming payload is an object, not an Array
Map<String, Set<String>> result = new HashMap<>();
try {
JSONArray albums = resourcesNode.getJSONArray("Resources"); // get to the
//Resource array, that holds desired data
for (int i = 0; i < albums.length(); i++) {
JSONObject album = albums.getJSONObject(i);
String id = album.getString("id"); //id was type of String, not int
if(album.has("roles")){ // not all entries had roles, safety check
Set<String> userRoles =new HashSet<>();
JSONArray roles = album.getJSONArray("roles");
for(int j=0;j<roles.length();j++){
userRoles.add(roles.get(j).toString());
}
results.put(id, userRoles);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return results;
}
i am trying to do an android app to write some datas on MySQL database but it does not work i did a Java class for this and i think the problem comes from this. Here is my code :
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
BackgroundTask(Context ctx) {this.ctx = ctx;}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://localhost:8080/project/register.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String password = params[2];
String contact = params[3];
String country = params[4];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&" +
URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(contact, "UTF-8") + "&" +
URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration success";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Actually what i would like is to save name, password, contact and country in my database. The problem is this : "Registration success" is never returned it is always null. But i don't know why. When i try to compile it looks like there is no errors and i can see the app.
Thank you very much for your help !
Edit : This is the register.php :
<?php
require "init.php";
$u_name=$_POST["name"];
$u_password=$_POST["password"];
$u_contact=$_POST["contact"]";
$u_country=$_POST["country"];
$sql_query="insert into users values('$u_name', '$u_password', '$u_contact', '$u_country');";
//mysqli_query($connection, $sql_query));
if(mysqli_query($connection,$sql_query))
{
//echo "data inserted";
}
else{
//echo "error";
}
?>
And also the init.php :
<?php
$db_name = "project";
$mysql_user = "root";
$server_name = "localhost";
$connection = mysqli_connect($server_name, $mysql_user, "", $db_name);
if(!$connection){
echo "Connection not successful";
}
else{
echo "Connection successful";
}
?>
Thank you for your help !
My class PutUtility for getData(), PostData, DeleteData(). you just need to change package name
package fourever.amaze.mics;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class PutUtility {
private Map<String, String> params = new HashMap<>();
private static HttpURLConnection httpConnection;
private static BufferedReader reader;
private static String Content;
private StringBuffer sb1;
private StringBuffer response;
public void setParams(Map<String, String> params) {
this.params = params;
}
public void setParam(String key, String value) {
params.put(key, value);
}
public String getData(String Url) {
StringBuilder sb = new StringBuilder();
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) { }
}
return response.toString();
}
public String postData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
value = params.get(key);
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return response.toString();
}
public String putData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
try {
value = URLEncoder.encode(params.get(key), "UTF-8");
if (value.contains("+"))
value = value.replace("+", "%20");
//return sb.toString();
// Get the server response
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send PUT data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("PUT");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(false);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
;
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb1.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
// Send PUT data request
return Url;
}
public String deleteData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("DELETE");
httpConnection.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb1.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
}
return Url;
}
}
And use this class like this
#Override
protected String doInBackground(String... params) {
res = null;
PutUtility put = new PutUtility();
put.setParam("ueid", params[0]);
put.setParam("firm_no", params[1]);
put.setParam("date_incorporation", params[2]);
put.setParam("business_name", params[3]);
put.setParam("block_no", params[4]);
try {
res = put.postData(
"Api URL here");
Log.v("res", res);
} catch (Exception objEx) {
objEx.printStackTrace();
}
return res;
}
#Override
protected void onPostExecute(String res) {
try {
} catch (Exception objEx) {
mProgressDialog.dismiss();
objEx.printStackTrace();
}
}
Please use this. Hope it helps you in future also.
Check this if this is the problem
$u_contact=$_POST["contact"]"
here is the problem i think so brother. replace with
$u_contact=$_POST["contact"];
Here i am attaching code and a link consist of full code , have a look on it:-
My authorization header seams to be coming of same length as mentioned in official site of payeezy.I have also make my hmacString of same order as mentioned in this link (https://developer.payeezy.com/content/hmac-validation-failure) . After doing all this i am still getting this same issue
public static String excutePost(String urlParameters) throws IOException {
URL url = new URL("https://api-cert.payeezy.com/v1/transactions");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
// Create connection
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", headerContentType);
connection.setRequestProperty("apikey ", apikey);
connection.setRequestProperty("token", MerchantToken);
connection
.setRequestProperty("Authorization", authorizationHeader);
connection.setRequestProperty("timestamp", ""+epoch);
connection.setRequestProperty("nonce", ""+nonce);
connection.setDoOutput(true);
connection.setReadTimeout(30000);
// Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
Here is full java class code :- http://piratepad.net/ep/pad/view/ro.WwZ9v6FX1a6/latest
I finally solve this error by sending direct String as parameter in api url hit.Here i am posting some of my code which solve my error :-
String str = "{\"amount\":\"1299\",\"merchant_ref\":\"Astonishing-Sale\",\"transaction_type\":\"authorize\",\"credit_card\":{\"card_number\":\"4788250000028291\",\"cvv\":\"123\",\"exp_date\": \"1020\",\"cardholder_name\": \"John Smith\",\"type\": \"visa\"},\"method\": \"credit_card\",\"currency_code\": \"USD\"}";
now this String will be used in generating my authorisation key.
the whole process is defined below :-
getSecurityKeys(apikey, pzsecret,str);
private static Map<String, String> getSecurityKeys(String appId,
String secureId, String payLoad) throws Exception {
Map<String, String> returnMap = new HashMap<String, String>();
try {
returnMap.put(NONCE, Long.toString(nonce));
returnMap.put(APIKEY, appId);
returnMap.put(TIMESTAMP, Long.toString(System.currentTimeMillis()));
returnMap.put(TOKEN, MerchantToken);
returnMap.put(APISECRET, pzsecret);
returnMap.put(PAYLOAD, payLoad);
returnMap.put(AUTHORIZE, getMacValue(returnMap));
authorizationHeader = returnMap.get(AUTHORIZE);
return returnMap;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public static String getMacValue(Map<String, String> data) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
String apiSecret = data.get(APISECRET);
SecretKeySpec secret_key = new SecretKeySpec(apiSecret.getBytes(),
"HmacSHA256");
mac.init(secret_key);
StringBuilder buff = new StringBuilder();
buff.append(data.get(APIKEY)).append(data.get(NONCE))
.append(data.get(TIMESTAMP));
if (data.get(TOKEN) != null)
buff.append(data.get(TOKEN));
if (data.get(PAYLOAD) != null)
buff.append(data.get(PAYLOAD));
byte[] macHash = mac.doFinal(buff.toString().getBytes("UTF-8"));
String authorizeString = Base64.encodeBase64String(toHex(macHash));
return authorizeString;
}
Now finally you can pass direct String(i.e str) as parameter in hitting post api in java.
hope it helps other to integrate payeezy payment gateway without using any dependencies.
Happy Codeing!!!
You must generate a new timestamp and nonce for every request, i.e., every new request must have its unique timestamp and nonce.
In java, timestamp can be set as System.currentTimeMillis() and nonce can be set using UUID (UUID.randomUUID().toString()).
Finally, make sure that your Authorization is correctly computed (I see they use HMAC-SHA1 using API secret key).
I hope this helps.
Edit: As suspected, it's your HMAC-SHA1 Authorization value that is incorrect. I get the following response when running your code (after few coding of my own).
Connection = keep-alive
Content-Length = 51
Content-Type = application/json
{"code":"403", "message":"HMAC validation Failure"}
Make sure that you compute your HMAC-SHA1 value correctly (as I said above).
See the below (updated) code that you can compile and run for yourself. You will need Java 8 as it comes with Base 64 encoder/decoder now.
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.net.URI;
import java.net.URL;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
//import org.apache.commons.codec.binary.Base64;
public class MainJava {
private static final String myEncoding = "UTF-8";
private static final String myMessageDigest = "SHA-1";
private static final String myKeySpec = "HmacSHA1";
private static String NEWLINE = "\n";
private static String authorizationHeader;
private static String contentSha1;
// private static String keyId = "230297";
// private static String hmacKey = "tcwR9r1OR85V9bcV5tc7a9d1XkWigjqY";
private static String ApiSecretkey = "0779eb593286b278aaf8cfcf83c8e33bc757d53a8a642b53d24d63bda844da5b";
private static String MerchantToken = "fdoa-a480ce8951daa73262734cf102641994c1e55e7cdf4c02b6";
private static String reportingToken = "e56a0223d0415067";
private static String apikey = "XSjbv8PLDINJ28qXLEYAhcrz8rxKXQ4Y";
private static long nonce;
public static String headerContentType = "application/json";
private static long epoch;
public static void main(String[] args) throws Exception {
String json_string_dataTwo = "{\"type\":\"visa\",\"cardholder_name\":\"John Smith\",\"card_number\":\"4788250000028291\",\"exp_date\":1020,\"cvv\":\"123\"}";
// String json_string =
// "{\"gateway_id\":\"AI2010-01\",\"password\":\"w226638qtot48xu503zumwt2iy46g26q\",\"transaction_type\":\"00\",\"amount\":10,\"cardholder_name\":\"test\",\"cc_number\":\"4111111111111111\",\"cc_expiry\":\"1219\"}";
String json_string_data = "{\"merchant_ref\":\"Astonishing-Sale\",\"transaction_type\":\"authorize\",\"method\":\"credit_card\",\"amount\":1299,\"currency_code\":\"USD\",\"credit_card\":"
+ json_string_dataTwo + "}";
// "{\r\n \"merchant_ref\": \"Astonishing-Sale\",\r\n \"transaction_type\": \"authorize\",\r\n \"method\": \"credit_card\",\r\n \"amount\": \"1299\",\r\n \"currency_code\": \"USD\",\r\n \"credit_card\": {\r\n \"type\": \"visa\",\r\n \"cardholder_name\": \"John Smith\",\r\n \"card_number\": \"4788250000028291\",\r\n \"exp_date\": \"1020\",\r\n \"cvv\": \"123\"\r\n }\r\n}";
epoch = System.currentTimeMillis();// / 1000;
// nonce = UUID.randomUUID().toString();
nonce = Math.abs(SecureRandom.getInstance("SHA1PRNG").nextLong());
contentSha1 = contentSha1(json_string_data);
authorizationHeader = authHeader(epoch, contentSha1);
System.out.println(excutePost(json_string_data));
}
private static String authHeader(long hashTime, String contentSha1) {
String authorizationHeader = null;
try {
String hmacString = "POST" + NEWLINE + "application/json" + NEWLINE + contentSha1 + NEWLINE + hashTime + NEWLINE + apikey + NEWLINE
+ new URI("https://api-cert.payeezy.com/v1/transactions");
return sha1(hmacString, ApiSecretkey);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String contentSha1(String content) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] sha1hash = new byte[40];
md.update(content.getBytes("UTF-8"), 0, content.length());
sha1hash = md.digest();
return convertToHex(sha1hash);
}
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = data[i] >>> 4 & 0xF;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) (48 + halfbyte));
else
buf.append((char) (97 + (halfbyte - 10)));
halfbyte = data[i] & 0xF;
} while (two_halfs++ < 1);
}
return buf.toString();
}
// private static String sha1(String s, String keyString) {
// Base64 base64 = new Base64();
// try {
// SecretKeySpec key = new SecretKeySpec(keyString.getBytes("UTF-8"),
// "HmacSHA1");
// Mac mac = Mac.getInstance("HmacSHA1");
// mac.init(key);
// byte[] bytes = mac.doFinal(s.getBytes("UTF-8"));
//
// return new String(base64.encode(bytes));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
private static String sha1(String s, String keyString) {
byte[] bytes = null;
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(keyString.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
bytes = sha256_HMAC.doFinal(s.getBytes("UTF-8"));
//return new String(Base64.encodeBase64String(bytes));
} catch (Exception e) {
System.out.println("Error");
}
return Base64.getEncoder().encodeToString(bytes);
}
private static String hashTime() {
String time = getUTCFormattedDate("yyyy-MM-dd'T'HH:mm:ss'Z'");
return time;
}
private static String getUTCFormattedDate(String format) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat.format(new Date());
}
public static String excutePost(String urlParameters) throws IOException {
System.out.println(urlParameters);
System.out.println(headerContentType);
System.out.println(MerchantToken);
System.out.println(authorizationHeader);
System.out.println(epoch);
System.out.println(nonce);
URL url = new URL("https://api-cert.payeezy.com/v1/transactions");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
// Create connection
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", headerContentType);
connection.setRequestProperty("apikey ", apikey);
connection.setRequestProperty("token", MerchantToken);
connection.setRequestProperty("Authorization", authorizationHeader);
connection.setRequestProperty("timestamp", "" + epoch);
connection.setRequestProperty("nonce", "" + nonce);
connection.setDoOutput(true);
connection.setReadTimeout(30000);
// Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = null;
int statusCode = connection.getResponseCode();
try {
is = connection.getInputStream();
} catch (IOException e) {
if (statusCode >= 400) {
is = connection.getErrorStream();
}
}
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
My only issue is with the character encoding, where I assume UTF-8. I suspect that the error lies elsewhere.
// Send request
byte[] data = urlParameters.getBytes(StandardCharsets.UTF_8);
BufferedOutputStream wr = new BufferedOutputStream(connection.getOutputStream());
wr.writeBytes(data);
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is,
StandardCharsets.UTF_8));
And \r, CR, does not serve as line separator (apart from old MacOS).
response.append("\r\n"); // Or '\n'
I am not sure why this url is throwing a MalformedURL exception: http%3A%2F%2Fapi.themoviedb.org%2F3%2Fsearch%2Fperson%3Fapi_key%3secret%26query%3Dchristopher_guest
This is the url required by the api that I need to use. http://api.themoviedb.org/3/search/person?api_key=secret&query=christopher_guest
I have been getting target host must not be null errors using this url then I changed my coded to what you are seeing below. Not sure whats going on here although I have heard urls that contain underscores dont validate outside of web browsers and cause these types of situations.
Any ideas around this?
This is where I build the url
package com.tot.tipofthetongue;
import android.widget.EditText;
public class getName {
static String nameOne = null;
static String nameTwo = null;
static StringBuilder personURLOne = new StringBuilder();
static StringBuilder personURLTwo = new StringBuilder();
public static String personURL = "http://api.themoviedb.org/3/search/person?api_key=secret&query=";
public static StringBuilder getName1(EditText searchOne){
nameOne = searchOne.getText().toString();
nameOne = nameOne.replace(" ", "_");
personURLOne.append(personURL);
personURLOne = personURLOne.append(nameOne);
return personURLOne;
}
And this is my jsonparser that I pass that url to.
public class JSONParser extends AsyncTask<String, Void, JSONObject> {
static InputStream inputStream = null;
static JSONObject jObject = null;
static String jSon = "";
public String myURL;
String host;
HttpRequest request;
protected JSONObject doInBackground(String... url) {
// TODO Auto-generated method stub
//Make HTTP Request
try {
//defaultHttpClient
for(int i = 0; i < url.length; i++){
myURL = url[0];
myURL = URLEncoder.encode(myURL, "utf-8");
}
HttpGet httpGet = new HttpGet(myURL);
//header
httpGet.setHeader("Accept", "application/json");
HttpResponse httpResponse = new DefaultHttpClient().execute(new HttpHost(new URL(myURL).getHost()), request);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
stringBuilder.append(line + "\n");
}
Log.d("JSON Contents", stringBuilder.toString());
inputStream.close();
jSon = stringBuilder.toString();
} catch (Exception e){
Log.e("Buffer Error", "Error converting result " + e.toString());
}
//try to parse the string to JSON Object
try {
jObject = new JSONObject(jSon);
} catch (JSONException e){
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//return JSON String
return jObject;
}
}
Print the String you formed before final submission to form Uri. And attach this to your question. It would be much easier to answer.
Try using HttpGet(URI uri) instead of HttpGet(String uri)
The reason is pretty simple. If you are using Uri, you will get immediately the Exception.
Hope this will help you to debug quickly.