Retrieve data from php - java

I have a small piece of code that makes a connection with a webpage. When I login Iretrieve the user_id from the database and put that in a textbox.
Then I want to retrieve the Firstname and Lastname from the database but when I do that I get a <br/> from the webpage. I cannot find out why I get the <br/> instead of the firstname.
This is my php code to handle the request that I get from Java
$user_id = $_SESSION['user'];
$voornaam = $con->select('voornaam', 'users', 'id', $user_id);
$achternaam = $con->select('achternaam', 'users', 'id', $user_id);
echo $voornaam;
public function select($detail, $table, $row, $value) {
$query = mysqli_query($this->connect, "SELECT `$detail` FROM `$table` WHERE `$row` = '$value'");
$associate = mysqli_fetch_assoc($query);
return $associate[$detail];
}
And this is the code that I use to send the data to php
public static String Select() {
String mysql_type = "2"; // 2 = Select
try {
String urlParameters = "mysql_type=" + mysql_type;
URL url = new URL("http://localhost:8080/HTTP_Connection/index.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while((line = reader.readLine())!= null)
{
return line;
}
writer.close();
reader.close();
return reader.readLine();
} catch (IOException iox) {
iox.printStackTrace();
return null;
}
}
Can someone explain to me why I get the <br/> instead of the first name?
Thanks in advance

It could be that in the line where you select the $voornaam:
"SELECT$detailFROM$tableWHERE$row= '$value'"
You use 3 different quotes:
U use ", ',
Try to replace thewith ' and then I think it should work.
So replace
"SELECT$detailFROM$tableWHERE$row= '$value'"
with "SELECT '$detail' FROM '$table' WHERE '$row' = '$value'"

Related

Can't send POST message over Https

I have a simple android app that needs to send a message to my PHP server, which will return some data back. I am able to get the data returned from the server, but I can't send any. It's probably something stupid, but I can't figure it out. Note that the url here isn't the real url.
public void addUser(User user, String password) throws Exception {
URL url = new URL("https://someuser.c9users.io/service.php");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// set Timeout and method
conn.setRequestMethod("POST");
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestProperty("op", "adduser");
conn.setDoOutput(true);
conn.setRequestProperty("username",user.getUserName());
conn.setRequestProperty("email",user.getEmail());
conn.setRequestProperty("password", password);
if(user.getBirthDate() != null)
conn.setRequestProperty("birthdate", user.getBirthDate().toString());
if(user.getProfImage() != null)
conn.setRequestProperty("profile_image", "some path to img");
//conn.connect(); if I leave the code it does NoFileFoundException. why?
InputStream is = conn.getInputStream();
String result="";
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result += inputLine;
}
}
my php code:
function print_post_get() {
echo "post&get vals: ";
foreach($_POST as $key => $value) {
echo $key.":".$value." \n";
}
foreach($_GET as $key => $value) {
echo $key.":".$value." \n";
}
}
//print all post and get
print_post_get();
//get method form post
if(empty($_POST['op']))
die('no operation?');
switch($_POST['op']) {
case 'adduser':
$retval = adduser();
if($retval) //couldn't add user
echo $retval;
break;
case 'removeuser':
$retval = removeuser();
if($retval)
echo $retval;
break;
case 'getuser':
$retval = getuser();
echo $retval;
break;
default:
echo "unknow op.";
break;
}
I recently had a similar problem. I found setRequestProperty adds to your headers, not the POST body. But the
conn.setDoOutput(true)
allows you to connect to the
outStream = conn.getOutputStream()
Now you can create the POST data with a android.net.Uri.Builder.
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username",user.getUserName())
.appendQueryParameter("email",user.getEmail());
Write to the stream, the getEncodedQuery()
try (OutputStream outStream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(outStream, "UTF-8"))) {
String query = builder.build().getEncodedQuery();
writer.write(query);
}
Now you can POST your request with conn.

Sending two values into php webpage with java

I am trying to send two string values from my java program into my php page and i seem to be having some difficulty figuring out how this all works.
public static void main (String args[]) throws IOException{
Scanner input = new Scanner (System.in);
String sampleValue = input.next();
String sampleValue1 = input.next();
URL url = new URL("http://woah.x10host.com/randomfact.php");
String result = "";
String data = "fName=" + URLEncoder.encode(sampleValue, "UTF-8");
String id = "lName=" + URLEncoder.encode(sampleValue1, "UTF-8");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// Send the POST data
DataOutputStream dataOut = new DataOutputStream(connection.getOutputStream());
dataOut.writeBytes(id);
dataOut.writeBytes(data);
dataOut.flush();
System.out.println("Data has been posted");
dataOut.close();
BufferedReader in = null;
try {
String line;
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = in.readLine()) != null) {
result += line;
}
} finally {
if (in != null) {
in.close();
}
}
} finally {
connection.disconnect();
System.out.println(result);
}
}
}
my PHP code is
<?php
$conn = mysqli_connect("localhost","woahx10h_funfact","spk","woahx10h_woah");
// CHECK CONNECTION
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$value_data = $_POST['fName'];
$value_id = $_POST['lName'];
echo $value_data;
echo $value_id;
$conn->close();
?>
However, every time i run the java program, values from both data and id seem to be stored in the $value. I want the value from data to be stored in $value_data while the value from x to be stored in $value_id
You have to add ampersand (&) between each two parameters. So in this case all you have to do is edit your code like this:
...
dataOut.writeBytes(id);
dataOut.writeBytes("&");
dataOut.writeBytes(data);
...
If you would want to add another parameter to the request you would have to add another ampersand and then the parameter, for example:
...
dataOut.writeBytes(id);
dataOut.writeBytes("&");
dataOut.writeBytes(data);
dataOut.writeBytes("&");
dataOut.writeBytes(parameter3);
...

Method to download website source returns nothing

I created method to download any url's source and show it in textview called checkView but when I call it with button it returns me empty textview instead of string with website code:
void getWebsite(String search) {
String res = null;
try {
StringBuffer sb = new StringBuffer("");
String line = "";
URL url = new URL("http://drinkify.org" + search);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String NL = System.getProperty("line.separator");
while ((line = rd.readLine()) != null) {
sb.append(line + NL);
res = sb.toString();
}
} catch (Exception e) {
}
checkView.setText(res);
}
Any thoughts?
First of all, add a log-statement or a breakpoint to see if the text is actually downloaded.
My guess is that you get an exception (missing INTERNET-permission in the manifest?) that gets swallowed in your catch (Exception e), add a breakpoint within the catch clause to test it.

Error when using java.net to connect to a website

I am trying to login to a website using java.net in Google App Engine for Java.
The login id and password are stored in variables 'loginid' and 'password' respectively.
The code that I have created is given below:
public Integer login()
{
String param1="", param2="", query="";
String charset = "UTF-8";
String loginurl = "https://website.com/login";
try {
param1 = URLEncoder.encode(loginid, "UTF-8");
param2 = URLEncoder.encode(password, "UTF-8");
query = String.format("username=%s&password=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
} catch (UnsupportedEncodingException ex) {
// ...
}
try {
URL url = new URL(loginurl + "?" + query);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line="";
String resp="";
while ((line = reader.readLine()) != null) {
resp=resp + line;
}
actionmessage=" Response-" + resp;
return(1);
}
catch (Exception e) {
// ...
}
}
I want to know more about a couple of things with ref to above code.
I am sure that I have entered correct ID and password, but still I am getting login failure. What is wrong with the above code?
How do I check if a submission as made by above code is successful or if there is an error? If there is an error, how do I get the error stream?
It was an error on my part- I encoded the 2 parameters passed to input url, twice!! So the site where I was authenticating, received a garbled value for user id and password!

Using Java to send data to a form on a website hosted locally

I have a program in Java where I retrieve contents from a database.
Now I have a form in the program, and what I want to do is, on the press of a button, some string (text) content retrieved from the database, should be sent over to a website that I'm hosting locally. The content so sent, should be displayed on the website when refreshed.
Can someone guide me as to how I can achieve this (the sending of data to be displayed over the website)?
Will appreciate a lot, if you could kindly show some sample snippets or give me a reference to some tutorial that can help.
---- Okay so i found a link to a snippet that's supposed to do this, but im unable to understand at this stage as to how exactly this snippet works...can someone please guide me into knowing this better ?
here's the code
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
I'm not sure on how you store and manage any of the records but from Java you can send a HTTP Post to the Url (In your case http://localhost/, probably).
Have a look at http://www.exampledepot.com/egs/java.net/post.html for a snippet on how to do this.
Your Website could then store the received information in a database and display it when you refresh.
Update heres the function
Just a side not this is by no means the best way to do this and I have no idea on how this scales but for simple solutions this has worked for me in the past.
/**
* Posts a Set of forms variables to the Remote HTTP Host
* #param url The URL to post to and read
* #param params The Parameters to post to the remote host
* #return The Content of the remote page and return null if no data was returned
*/
public String post(String url, Map<String, String> params) {
//Check if Valid URL
if(!url.toLowerCase().contains("http://")) return null;
StringBuilder bldr = new StringBuilder();
try {
//Build the post data
StringBuilder post_data = new StringBuilder();
//Build the posting variables from the map given
for (Iterator iter = params.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
String value = (String)entry.getValue();
if(key.length() > 0 && value.length() > 0) {
if(post_data.length() > 0) post_data.append("&");
post_data.append(URLEncoder.encode(key, "UTF-8"));
post_data.append("=");
post_data.append(URLEncoder.encode(value, "UTF-8"));
}
}
// Send data
URL remote_url = new URL(url);
URLConnection conn = remote_url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(post_data.toString());
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = rd.readLine()) != null) {
bldr.append(inputLine);
}
wr.close();
rd.close();
} catch (Exception e) {
//Handle Error
}
return bldr.length() > 0 ? bldr.toString() : null;
}
You would then use the function as follows:
Map<String, String> params = new HashMap<String, String>();
params.put("var_a", "test");
params.put("var_b", "test");
params.put("var_c", "test");
String reponse = post("http://localhost/", params);
if(reponse == null) { /* error */ }
else {
System.out.println(reponse);
}
The big question is how will you authenticate the "update" from your Java program to your website?
You could easily write a handler on your website, say "/update" which saves the POST body (or value of a request parameter) to a file or other persistent store but how will you be sure that only you can set that value, instead of anybody who discovers it?

Categories