Sending two values into php webpage with java - 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);
...

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.

URLConnection and POST method android

I am trying to make a post request using the reference of this documentation. But the problem is that the PHP developer at the other end is not able to receive the value of the parameter hence is not able to send a proper response. Am I missing something out here.
// Edits ;
I am making a HTTP Post request. As you can seen the code below. I am writing the arguments and parameters (location_id=3) to the outputstream. I have also pasted the code for PHP which i have been using. Now the problem is:
The parameter value ( which is 3 ) is not received at the PHP code so I am getting a response which is surrounded by the else block. So I just want to know if there is an error in the android code or the PHP code
#Override
protected Boolean doInBackground(String... params) {
Log.d(Constants.LOG_TAG,Constants.FETCH_ALL_THEMES_ASYNC_TASK);
Log.d(Constants.LOG_TAG," The url to be fetched "+params[0]);
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
// /* optional request header */
// urlConnection.setRequestProperty("Content-Type", "application/json");
//
// /* optional request header */
// urlConnection.setRequestProperty("Accept", "application/json");
/* for Get request */
urlConnection.setChunkedStreamingMode(0);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("location_id",params[1]));
outputStream = urlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(writeToOutputStream(nameValuePairs));
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
response = convertInputStreamToString(inputStream);
Log.d(Constants.LOG_TAG, " The response is " + response);
return true;
}
else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(inputStream != null){
inputStream.close();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
// Here is the code for writeToOutputStream
public String writeToOutputStream(List<BasicNameValuePair> keyValuePair)throws UnsupportedEncodingException{
String result="";
boolean firstTime = true;
for(BasicNameValuePair pair : keyValuePair){
if(firstTime){
firstTime = false;
}
else{
result = result.concat("&");
}
result = result + URLEncoder.encode(pair.getKey(), "UTF-8");
result = result + "=";
result = result+ URLEncoder.encode(pair.getValue(),"UTF-8");
}
Log.d(Constants.LOG_TAG," The result is "+result);
return result;
}
// Here is the code for convertInputStream to String
public String convertInputStreamToString(InputStream is) throws IOException {
String line="";
String result="";
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
while((line = bufferedReader.readLine()) != null){
Log.d(Constants.LOG_TAG," The line value is "+line);
result += line;
}
/* Close Stream */
if(null!=inputStream){
inputStream.close();
}
return result;
}
Here is the PHP CODE
<?php
include 'config.php';
header ('Content-Type:application/json');
if(isset($_POST['location_id']))
{
$id=$_POST['location_id'];
$selectThemeQuery = mysql_query("select theme_id from location_theme where location_id='$id'",$conn) or die (mysql_error());
$noRows = mysql_num_rows($selectThemeQuery);
//echo "HI";
if($noRows > 0)
{
$result = array();
while($row = mysql_fetch_assoc($selectThemeQuery))
{
$themeid = $row['theme_id'];
//echo "HI";
$selectNameQuery = mysql_query("select theme_name,theme_image from theme where theme_id='$themeid'",$conn) or die(mysql_error());
$numRows = mysql_num_rows($selectNameQuery);
if($numRows > 0)
{
while($rows = mysql_fetch_assoc($selectNameQuery))
{
$name = $rows['theme_name'];
$image = $rows['theme_image'];
$result[] = array('theme_id'=>$themeid,'theme_name'=>$name, 'theme_image'=>$image);
}
}
}
//echo json_encode($result);
echo json_encode("Hi");
}
else
{
$data2[] = array('Notice'=>false);
echo json_encode($data2);
}
}
else
{
echo "Not Proper Data";
}
?>
Remove:
urlConnection.setChunkedStreamingMode(0);
You use a buffered writer so it can only buffer instead of write.
To force all been written:
bufferedWriter.write(writeToOutputStream(nameValuePairs));
bufferedWriter.flush();
And then ask for a response code. And don't call a response code a status code.
writeToOutputStream() ??? What a terrible name. That function does not write to an output stream. It justs makes a text string.
For Android, I would suggest using a library like Spring-Android.
Spring-Android contains a RestTemplate class, which is a quite effective REST-Client. For example, a simple POST request would be...
myRestTemplate.exchange("http://www.example.net", HttpMethod.POST, new HttpEntity( ...some JSON string ...), String.class );
To create the JSON String, I suggest a library like Jackson, which should work fine on Android, see for example here. Not sure if Jackson integrates as fine in Spring-Android as it does in Spring-Web, but in any case, using it to create the Json Strings manually should work just fine.
for post method
create a string builder first
StringBuilder strbul=new StringBuilder();
then append the data like
strbul.append("name=sangeet&state=kerala");
then write to output stream like
httpurlconnection.getOutput().write(strbul.toString().getBytes("UTF-8"));
php script will recieve that data on
$_POST['name'] and $_POST['state']

Java CURL request using HTTP

I am trying to perform a CURL request using Java. The CURL request is as follows:
curl https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1 -u username:password
I am trying to perform the request as follows:
String stringUrl = "https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());
and I am trying to see the contents of inputStreamReader as follows:
int data = inputStreamReader.read();
char aChar = (char) data;
System.out.println(aChar);
The code is compiling and running fine, but it is returning nothing. Where am I going wrong?
I ended up getting it working using the following code:
public static void main(String args[]) throws IOException {
String stringUrl = "url";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
StringBuilder html = new StringBuilder();
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String htmlLine;
while ((htmlLine = input.readLine()) != null) {
html.append(htmlLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(html.toString());
}
I was also trying to do that thing. I have some kind of workaround but it reads everything it sees.
--Here's the code---
String params = "some-parameters";
URL url = new URL("some-website");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
con.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer();
while((line = reader.readLine()) != null) {
buffer.append(line+"\n");
}
reader.close();
System.out.print(buffer.toString());
--Notice, I use this code to see if a certain account exist on a certain website, since it outputs everything, what I do is to find a specific regularity upon the code which could tell me if that user exist or not. Well I'm not really even sure if this could help you, but it might be. Good Luck...

Retrieve data from php

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'"

Web content is different using Java than in browser

I have strange problem with BufferedReader reading from web.
This URL content is different in browsers than in pasted Java code.
In content fetched using Java first elements result is empty in browser it is not.
My code:
public static void main(String[] args) {
try {
String url = "https://api.freebase.com/api/service/mqlread?queries={\"q1\":{\"query\":[{\"name\":\"Pulp Fiction\",\"*\":null,\"type\":\"/film/film\"}]},\"q3\":{\"query\":[{\"name\":\"Portal\",\"*\":null,\"type\":\"/cvg/computer_videogame\"}]}}";
URL u = new URL(url);
System.out.println(u.toString());
URLConnection urlConn = u.openConnection();
InputStreamReader is = new InputStreamReader(urlConn.getInputStream());
BufferedReader br = new BufferedReader(is);
String line = null;
String data = "";
while ((line = br.readLine()) != null) {
data += line + "\n";
}
br.close();
System.out.println(data);
} catch (Exception ex) {
System.err.println(ex);
}
}
EDIT: Ahh. Figured it out. No space characters in URLs. Just replace them with %20.

Categories