How can I send Post Values to a PHP File?
So that the PHP File can send this value for example to a databse or something else.
So that I can send a string from my java file to the php file that works with it.
As i answered some time ago, i made a class for this, hope it helps.
However, you should show us what you have tried instead of just asking.
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Vector;
public class SiteFX {
private String postParameters = "";
private String webPage;
private Vector<String>names;
private Vector<String>values;
public SiteFX(){
values = new Vector<String>();
names = new Vector<String>();
}
/**
* Adds a post variable (page.php?name=value)
*
* #param name the variable name
* #param value the variable value, can be set to null, the url will simply become &name instead of &name=value
* null
*/
public void addPostValue(String name, String value) {
if (value == null) {
try {
postParameters += "&" + URLEncoder.encode(name, "UTF-8");
names.add(name);
values.add("");
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
postParameters += "&" + URLEncoder.encode(name, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
names.add(name);
values.add(value);
}
}
/**
* Send post data without waiting for site output
*
* #return true if sending data terminated succesfully
*/
public boolean sendPost() {
try {
if (webPage == null || webPage.equals("")) {
throw new Exception("Empty url");
}
URL url = new URL(webPage);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(postParameters);
wr.flush();
} catch (Exception e) {
e.printStackTrace();
return false;
}
postParameters = "";
return true;
}
/**
* Sends data, then waits for site output
*
* #return null if no data is received, or a String containing the data
*/
public String sendPostWithReturnValue() {
String returnValue = "";
try {
if (webPage == null || webPage.equals("")) {
throw new Exception("Empty url");
}
URL url = new URL(webPage);
URLConnection conn =
url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr =
new OutputStreamWriter(conn.getOutputStream());
wr.write(postParameters);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
returnValue += line + "\n";
}
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
postParameters = "";
values = null;
names=null;
values = new Vector<String>();
names = new Vector<String>();
return returnValue;
}
/**
* Sets the page to point at for sending post variables
*
* #param webPageToPointAt the page that will receive your post data
*/
public void setWebPageToPointAt(String webPageToPointAt) {
webPage = webPageToPointAt;
}
/**
* #returns A Nx2 matrix containing all parameters name and values
*/
public String[][] getParameters() {
String[][] str = new String[names.size()][2];
for (int i = 0; i < str.length; i++) {
str[i][0] = names.get(i);
str[i][1] = values.get(i);
}
return str;
}
}
Related
VerifyRecaptcha class
public class VerifyRecaptcha {
public static final String url = "https://www.google.com/recaptcha/api/siteverify";
public static final String secret = "6LcIicUUAAAAAOeuLpcAVmE53PYtPphreUT9FuVg";
private final static String USER_AGENT = "Mozilla/5.0";
public static boolean verify(String gRecaptchaResponse) throws IOException {
if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
return false;
}
try {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en:q=0.5");
String postParams = "secret" + secret + "&response=" + gRecaptchaResponse;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters :" + postParams);
System.out.println("Response Code :" + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println("test "+ response.toString());
// parse JSON response and return 'success' value
JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
return jsonObject.getBoolean("success");
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
LoginController class
#Controller
public class LoginController {
/*
* ========================================================================
* Constants
* ========================================================================
*/
/** Attribute name msg */
private static final String ATTRIBUTE_NAME_MSG = "msg";
/** Attribute name error */
private static final String ATTRIBUTE_NAME_ERROR = "error";
/** Attribute value Login detail */
private static final String ATTRIBUTE_VAL_MSG_LOGIN_DETAIL = "Please Enter Your Login Details";
/** Attribute value invalid user name and password */
private static final String ATTRIBUTE_VAL_INVALID = "Invalid username and password";
/** Attribute value enter user name and password */
private static final String ATTRIBUTE_VAL_ENTER_USR_PWD = "Please enter username and password.";
/** Attribute value verify Recaptcha */
private static final String ATTRIBUTE_VAL_ENTER_RECAPTCHA = "Please verify captcha.";
/** Path to file connection DataBase */
private static final String RESOURCE_PATH = "e7bankaccountprinting/config/mybatis-config.xml";
/*
* ========================================================================
* RequestMapping
* ========================================================================
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String init(Model model) {
// model.addAttribute(ATTRIBUTE_NAME_MSG,ATTRIBUTE_VAL_ENTER_USR_PWD);
System.out.println("model test");
return "login";
}
/*
* String gRecaptchaResponse = loginBean.getgRecaptchaResponse()
* System.out.println("captcha response "+gRecaptchaResponse); boolean verify =
* VerifyRecaptcha.verify(gRecaptchaResponse);
*/
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String submit(Model model, #ModelAttribute("loginBean") LoginBean loginBean, HttpServletRequest req)
throws IOException {
String gRecaptchaResponse = req.getParameter("g-recaptcha-response");
System.out.println(gRecaptchaResponse);
boolean verify = VerifyRecaptcha.verify(gRecaptchaResponse);
System.out.println(verify);
if (loginBean != null && loginBean.getUserName() != null && loginBean.getPassword() != null
&& verify != false) {
SqlSession sqlSession = Connection.sqlSession(RESOURCE_PATH);
AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
// Set parameters to Account
Account inputAccount = new Account();
inputAccount.setUserName(loginBean.getUserName());
inputAccount.setPassword(loginBean.getPassword());
Account rs_account = accountMapper.getAccount(inputAccount);
if (rs_account != null) {
// if(inputAccount.setUserName(loginBean.getUserName()!=null)){
model.addAttribute(ATTRIBUTE_NAME_MSG, "Welcome " + loginBean.getUserName());
sqlSession.close();
return "A4Print";
} else {
model.addAttribute(ATTRIBUTE_NAME_ERROR, ATTRIBUTE_VAL_INVALID);
sqlSession.close();
return "login";
}
} else {
model.addAttribute(ATTRIBUTE_VAL_ENTER_USR_PWD, ATTRIBUTE_VAL_ENTER_RECAPTCHA);
return "login";
}
}
/*
* ========================================================================
* private method
* ========================================================================
*/
}
The error message
Sending 'POST' request to URL : https://www.google.com/recaptcha/api/siteverify
Post parameters : secret6LcIicUUAAAAAOeuLpcAVmE53PYtPphreUT9FuVg&response=03AO
LTBLSWWCbUzVHAfCZRYgrsnTt6VpW1nRx0NzI0FXUL1lngDgrSBbZbth0G5drjVCn6dtFBaygHibx7mRhkkI2cMJa0u0X9ls-
Response Code :200
TEst { "success": false, "error-codes": [ "missing-input-secret" ]}
false
The error message is pretty clear.
Shouldn't it be something like
//added missing = after secret
`String postParams = "secret=" + secret + "&response=" + gRecaptchaResponse;`
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"];
I have a class that has two methods that have a lot of duplicate code but the bit that's unique is in the middle of the whole thing. From my research I think I should be doing the "Execute around method" pattern but I can't find a resource that I can follow as they all seem to use code I can't replicate.
I have two methods, apiPost and apiGet, which I've pasted below. I've wrapped the unique parts of these methods with comments showing where the unique section starts and ends:
/**
* Class that handles authorising the connection and handles posting and getting data
*
* #version %I%, %G%
* #since 1.0
*/
public class CallHandler {
private static PropertyLoader props = PropertyLoader.getInstance();
final static int MAX = props.getPropertyAsInteger(props.MAX_REQUESTS);
private final Logger log = LoggerFactory.getLogger(CallHandler.class);
private final static String POST = "POST";
private final static String GET = "GET";
/**
* Makes a POST call to the API URL provided and returns the JSON response as a string
* http://stackoverflow.com/questions/15570656/how-to-send-request-payload-to-rest-api-in-java
*
* #param urlString the API URL to send the data to, as a string
* #param payload the serialised JSON payload string
* #return and value returned as a JSON string, ready to be deserialised
*/
public String apiPost(String urlString, String payload) {
boolean keepGoing = true;
int tries = 0;
String line;
StringBuilder jsonString = new StringBuilder();
log.debug("Making API Call: {}", urlString);
while (keepGoing && tries < MAX) {
tries++;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// UNIQUE CODE START
prepareConnection(connection, POST);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
// UNIQUE CODE END
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
keepGoing = false;
} catch (Exception e) {
log.warn("Try #{}. Error posting: {}", tries, e.getMessage());
log.warn("Pausing for 1 second then trying again...");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException f) {
log.warn("Sleeping has been interrupted: {}", f.getMessage());
}
}
}
return jsonString.toString();
}
/**
* Makes a GET call to the API URL provided and returns the JSON response as a string
* http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests
*
* #param urlString the API URL to request the data from, as a string
* #return the json response as a string, ready to be deserialised
*/
public String apiGet(String urlString) {
boolean keepGoing = true;
int tries = 0;
String line;
StringBuilder jsonString = new StringBuilder();
log.debug("Making API Call: {}", urlString);
while (keepGoing && tries < MAX) {
tries++;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// UNIQUE CODE START
prepareConnection(connection, GET);
connection.connect();
// UNIQUE CODE END
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
keepGoing = false;
} catch (Exception e) {
log.warn("Try #{}. Error getting from API: {}", tries, e.getMessage());
log.warn("Pausing for 1 second then trying again...");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException f) {
log.warn("Sleeping has been interrupted: {}", f.getMessage());
}
}
}
return jsonString.toString();
}
/**
* Prepares the HTTP Url connection depending on whether this is a POST or GET call
*
* #param connection the connection to prepare
* #param method whether the call is a POST or GET call
*/
private void prepareConnection(HttpURLConnection connection, String method) {
String charset = "UTF-8";
try {
connection.setRequestMethod(method);
if (method.equals(GET)) {
connection.setRequestProperty("Accept-Charset", charset);
} else if (method.equals(POST)) {
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json; charset=" + charset);
}
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + apiKey);
} catch (Exception e) {
log.error("Error preparing HTTP URL connection: {}", e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
Can I use the "Execute around method" pattern to save on code duplication here? If so could someone help me figure out how to refactor this code to make use of it. If this is the wrong way to go about it could someone suggest a smart alternative?
It can be done by extracting "unique" code into special worker. More specifically for example, you can use lambda expressions:
public String apiPost(String urlString, String payload) {
return commonMethod(urlString, payload, (connection) -> {
// UNIQUE CODE START
prepareConnection(connection, POST);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
// UNIQUE CODE END
});
}
interface ConnectionWorker {
void run(HttpURLConnection connection) throws IOException;
}
public String commonMethod(String urlString, String payload, ConnectionWorker worker) {
boolean keepGoing = true;
int tries = 0;
String line;
StringBuilder jsonString = new StringBuilder();
log.debug("Making API Call: {}", urlString);
while (keepGoing && tries < MAX) {
tries++;
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
worker.run(connection);
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
keepGoing = false;
} catch (Exception e) {
log.warn("Try #{}. Error posting: {}", tries, e.getMessage());
log.warn("Pausing for 1 second then trying again...");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException f) {
log.warn("Sleeping has been interrupted: {}", f.getMessage());
}
}
}
return jsonString.toString();
}
UPDATE: In case if you can not use java 8 and lambda, you can always switch to creating anonymous class:
return commonMethod(urlString, payload, new ConnectionWorker() {
#Override
public void run(HttpURLConnection connection) throws IOException {
// UNIQUE CODE START
CallHandler.this.prepareConnection(connection, POST);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
// UNIQUE CODE END
}
});
I have a rest webservice java class implemented in a project called pmtv2, and i want to call it from an other class in an other project called sigac as you can see in the picture.
here it is the WService class included in a package in pmtv2
package cat.diba.jee.pmtv2.ws.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cat.diba.jee.pmtv2.ws.rest.manager.RealitzarExpedientManager;
import cat.diba.jee.pmtv2.ws.rest.manager.RealitzarTramitManager;
import cat.diba.jee.pmtv2.ws.rest.message.RestMessage;
import cat.diba.jee.pmtv2.ws.rest.object.RespostaExpedient;
import cat.diba.jee.pmtv2.ws.rest.object.RespostaRealitzarTramit;
import cat.diba.jee.pmtv2.ws.rest.utils.TokenUtils;
/**
* The Class PmtRestWsService.
*/
#Path("/tramitacio")
public class PmtRestWsService {
/**
* The Constant CLASS_ID.
*/
private static final String CLASS_ID = PmtRestWsService.class.getName();
/**
* Log de la classe.
*/
private static final Log LOG = LogFactory.getLog(CLASS_ID);
/**
* The Constant PARAM_SESSION.
*/
private static final String PARAM_SESSION = "session";
/**
* The Constant PARAM_TOKEN.
*/
private static final String PARAM_TOKEN = "token";
/**
* The Constant PARAM_USERNAME.
*/
private static final String PARAM_USERNAME = "username";
/**
* The Constant PARAM_TRAMITS.
*/
private static final String PARAM_TRAMITS = "tramits";
/**
* The constants PARAM_EXPEDIENTS
*/
private static final String PARAM_EXPEDIENTS = "expedients";
/**
* Realitzar tramit.
*
* #param params the params
* #return the pmt expedient
*/
#POST
#Path("/realitzarTramit")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json,application/xml")
public RespostaRealitzarTramit realitzarTramit(String params) {
LOG.debug("Parametres = " + params);
RealitzarTramitManager manager = new RealitzarTramitManager();
RespostaRealitzarTramit resposta = new RespostaRealitzarTramit();
JSONObject jsonObject = new JSONObject(params);
try {
if (validarParametresEntrada(jsonObject)) {
String session = jsonObject.getString(PARAM_SESSION);
String token = jsonObject.getString(PARAM_TOKEN);
if (TokenUtils.validarToken(session, token)) {
resposta = manager.realitzarTramits(jsonObject, jsonObject.getString(PARAM_USERNAME));
} else {
//Token no validat
resposta.setTramitOK(false);
resposta.setError(RestMessage.ERROR_TOKEN_INVALID.getMessage());
}
} else {
//Paràmetres invàlids
resposta.setTramitOK(false);
resposta.setError(RestMessage.ERROR_REALITZAR_TRAMIT_PARAMETRES_ENTRADA.getMessage());
}
} catch (Exception e) {
// Errors als paràmetres d'entrada
LOG.error("ERROR : " + e.getMessage() + " - ORIGEN : " + e.getStackTrace()[0]);
resposta.setTramitOK(false);
resposta.setError(RestMessage.ERROR_REALITZAR_TRAMIT_NO_CONTROLAT.getMessage());
return resposta;
}
return resposta;
}
/**
* Realitzar tramit.
*
* #param params the params
* #return the pmt expedient
*/
#POST
#Path("/expedient")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json,application/xml")
public RespostaExpedient realitzarExpedient(String params) {
LOG.debug("Parametres = " + params);
RealitzarExpedientManager manager = new RealitzarExpedientManager();
RespostaExpedient resposta = new RespostaExpedient();
JSONObject jsonObject = new JSONObject(params);
try {
if (validarParametresEntradaExpedient(jsonObject)) {
String session = jsonObject.getString(PARAM_SESSION);
String token = jsonObject.getString(PARAM_TOKEN);
if (TokenUtils.validarToken(session, token)) {
resposta = manager.realitzarExpedients(jsonObject, jsonObject.getString(PARAM_USERNAME));
} else {
//Token no validat
resposta.setExpedientOK(false);
resposta.setCodiError(901);
resposta.setError(RestMessage.ERROR_TOKEN_INVALID.getMessage());
}
} else {
//Paràmetres invàlids
resposta.setExpedientOK(false);
resposta.setCodiError(902);
resposta.setError(RestMessage.ERROR_REALITZAR_EXPEDIENT_PARAMETRES_ENTRADA.getMessage());
}
} catch (Exception e) {
// Errors als paràmetres d'entrada
LOG.error("ERROR : " + e.getMessage() + " - ORIGEN : " + e.getStackTrace()[0]);
resposta.setExpedientOK(false);
resposta.setCodiError(998);
resposta.setError(RestMessage.ERROR_REALITZAR_EXPEDIENT_NO_CONTROLAT.getMessage());
return resposta;
}
return resposta;
}
/**
* validacio de entrada de expedients
*
* #param jsonObject
* #return
*/
private boolean validarParametresEntradaExpedient(JSONObject jsonObject) {
LOG.debug("validarPeticio(jsonObject) - Inici");
boolean result = true;
try {
jsonObject.getJSONArray(PARAM_EXPEDIENTS);
jsonObject.getString(PARAM_USERNAME);
jsonObject.getString(PARAM_SESSION);
jsonObject.getString(PARAM_TOKEN);
} catch (Exception e) {
result = false;
}
LOG.debug("validarParametresEntrada(jsonObject) - Fi");
return result;
}
/**
* Validar parametres entrada.
*
* #param jsonObject the json object
* #return true, if successful
*/
private boolean validarParametresEntrada(final JSONObject jsonObject) {
LOG.debug("validarPeticio(jsonObject) - Inici");
boolean result = true;
try {
jsonObject.getJSONArray(PARAM_TRAMITS);
jsonObject.getString(PARAM_USERNAME);
jsonObject.getString(PARAM_SESSION);
jsonObject.getString(PARAM_TOKEN);
} catch (Exception e) {
result = false;
}
LOG.debug("validarParametresEntrada(jsonObject) - Fi");
return result;
}
}
is there any way to do it ??
JAX-RS Client API
You can try the JAX-RS Client API, which provides a high-level API for accessing any REST resources. The Client API is defined in the javax.ws.rs.client package.
To access a REST resource using the Client API, you need the following steps:
Obtain an instance of the javax.ws.rs.client.Client interface.
Configure the Client instance with a target.
Create a request based on the target.
Invoke the request.
Example
Try the following to access your webservice (just change the URI paths according to your needs):
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080")
.path("pmtv2")
.path("api")
.path("tramitacio")
.path("realitzarTramit");
RespostaExpedient response = target.request(MediaType.APPLICATION_JSON)
.post(Entity.json(data)), RespostaExpedient.class);
More information
You will need an implementation of the JAX-RS Client API, such as Jersey or RESTEasy.
you should have an application server, you can use tomcat on localhost, and from the other project you just send à Request on your rest url : localhost[portNumber]/[yourRestService]
you can see this : How to send HTTP request in java?
You can do a http getrequest to your webservice with required paramters. For that you will need to add httpclient jar in your project.
For httpget request to work you must deploy your webservice on application server like tomcat or jboss or glassfish.
//Creating http client
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("localhost:8080/pmtv2/tramitacio/realitzarTramit?params="+params); // call to your webservice with required parameters
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
//receiving response
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
Publish the aplication in an aplication server (Tomcat?), obtain a URL where it is published and use some code like this to call it:
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
URL url = new URL(desturl);
huc.setRequestMethod("GET");
byte[] postData = null;
int postDataLength;
huc.setDoOutput(true);
postData = data.getBytes( StandardCharsets.UTF_8 );
postDataLength = postData.length;
huc.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
huc.setRequestProperty( "charset", "utf-8");
huc.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
huc.connect();
rd = new BufferedReader(new InputStreamReader(huc.getInputStream()));
retcode = huc.getResponseCode();
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