Sending POST Request headers to web server - java

I am trying to send a POST request to a php file located on a web server. Currently I am successfully sending the request but the headers are not being sent correctly.
Below is my query string I would like to send:
lastName=Jones&title=Android+Game+Programming+2&price=22.99&isbn=9876543210123&year=2012&firstName=Joe&publisher=Android+Press
and this is how I attempt to send them to the server:
if(method.equalsIgnoreCase("POST")){
//Write the http post request to web server
s.getOutputStream().write(("POST " + path + " HTTP/1.0\r\n").getBytes("ASCII"));
s.getOutputStream().write("Host: www.jdiadt.com\r\n\r\n".getBytes("ASCII"));
//Request Headers
String title = "title: "+request.getParameters().get("title") + "\r\n";
String firstName = "firstName: "+request.getParameters().get("firstName") + "\r\n";
String lastName = "lastName: " + request.getParameters().get("lastName") + "\r\n";
String isbn = "isbn: " + request.getParameters().get("isbn") + "\r\n";
String publisher = "publisher: " + request.getParameters().get("publisher") + "\r\n";
String year = "year: " + request.getParameters().get("year") + "\r\n";
String price = "price: " + request.getParameters().get("price") + "\r\n";
s.getOutputStream().write(title.getBytes("ASCII"));
s.getOutputStream().write(firstName.getBytes("ASCII"));
s.getOutputStream().write(lastName.getBytes("ASCII"));
s.getOutputStream().write(isbn.getBytes("ASCII"));
s.getOutputStream().write(publisher.getBytes("ASCII"));
s.getOutputStream().write(year.getBytes("ASCII"));
s.getOutputStream().write(price.getBytes("ASCII"));
//Blank line
String blankline = "\r\n";
s.getOutputStream().write(blankline.getBytes("ASCII"));
//Flush and wait for response...
s.getOutputStream().flush();
When I run the code I get this notice from the script which leads me to believe I am not sending the headers correctly:
Notice: Undefined index: title in C:\wamp\www\bookstore\createBook.php on line 3
It gives above error for every single line where I try to retrieve the variables sent via POST. Here is code:
$title = $_POST['title'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$publisher = $_POST['publisher'];
$isbn = $_POST['isbn'];
$year = $_POST['year'];
$price = $_POST['price'];
Any information as to what might be wrong?
createBook.php
<?php
$title = $_POST['title'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$publisher = $_POST['publisher'];
$isbn = $_POST['isbn'];
$year = $_POST['year'];
$price = $_POST['price'];
try {
require_once 'BookDAO.php';
require_once 'Book.php';
$dao = new BookDAO();
$book = new Book(NULL, $title, $firstName, $lastName,
$publisher, $isbn, $year, $price);
$dao->insert($book);
$books = $dao->findAll();
if (count($books) > 0) {
echo '<table>';
echo '<tr>';
echo ' <th>Title</th>
<th>First name</th>
<th>Last name</th>
<th>Year</th>
<th>Price</th>
<th>Actions</th>';
echo '</tr>';
foreach ($books as $book) {
echo '<tr>';
echo '<td>' . $book->getTitle() . '</td>';
echo '<td>' . $book->getFirstName() . '</td>';
echo '<td>' . $book->getLastName() . '</td>';
echo '<td>' . $book->getYear() . '</td>';
echo '<td>' . $book->getPrice() . '</td>';
echo '<td>';
echo '<a href="editBookForm.php?id=' . $book->getId() . '">';
echo '<img src="images/edit20.png" alt="Edit Book" />';
echo '</a>';
echo '<a href="deleteBook.php?id=' . $book->getId() . '"';
echo ' onclick="return confirm(\'Are you sure you want to delete';
echo ' this book?\');">';
echo '<img src="images/delete20.png" alt="Delete Book" />';
echo '</a>';
echo '</td>';
echo '</tr>';
}
echo '</table>';
}
else {
echo "<p>There are no books in the database.</p>";
}
echo '<p>';
echo '<a href="createBookForm.php">';
echo '<img src="images/new20.png" alt="New Book" /> New Book';
echo '</a>';
echo '</p>';
}
catch (PDOException $e) {
exit("Connection failed: " . $e->getMessage());
}
?>

Why not use a library like HttpClient? It's got a really nice API for performing HTTP GET, POST and other methods. It will allow you to write code that's less fragile and more understandable.
Link: http://hc.apache.org/httpclient-3.x/

You are setting your parameters in a GET-type (querystring) of way and are trying to get them using POST. You should change either of those so that they are the same.

I fixed the problem myself. For anyone wondering what I did here is my solution.
As you can see in the above code I included with my original question I was trying to send the headers one after the other which is the complete wrong thing to do!
I checked out the following two links (the second one particularly) and found them very helpful in explaining the POST request structure.
http://net.tutsplus.com/tutorials/other/http-headers-for-dummies/
http://ruturajv.wordpress.com/2005/12/25/http-post-request/
I then went back to my code and made the following changes to how I constructed my post request:
//POST REQUEST
if(method.equalsIgnoreCase("POST")){
//CONSTRUCT REQUEST
String blankline = "\r\n";
String query = request.getQueryString();
String length = String.valueOf(query.length());
System.out.println(length);
//Write the http post request to web server
s.getOutputStream().write(("POST " + path + " HTTP/1.0" +"\r\n").getBytes("ASCII"));
s.getOutputStream().write(("Host: localhost.com" + "\r\n").getBytes("ASCII"));
s.getOutputStream().write(("Content-Type: application/x-www-form-urlencoded"+"\r\n").getBytes("ASCII"));
s.getOutputStream().write(("Content-Length: " + length + "\r\n").getBytes("ASCII"));
s.getOutputStream().write(blankline.getBytes("ASCII"));
s.getOutputStream().write(query.getBytes("ASCII"));
//Flush and wait for response...
s.getOutputStream().flush();
I then simply read the response back from the server.

Related

Send https get request

I am working on a crawler and I have the following question: it works with simple HTTP requests, but not HTTPS, and I need to make an HTTPS request. I changed the port to 443 and try to send the same request, but I get 400 error. Obviously, I need to change something else, but I do not know what. I open socket and this is how I make the request:
String request
= "GET " + file
+ (file.endsWith("robots.txt") ? " HTTP/1.0\r\n" : " HTTP/1.1\r\n")
// " HTTP/1.1\r\n"
+ "User-Agent: " + CrawlerConfig.USER_AGENT + "\r\n"
// + ((!CrawlerConfig.SAVE_IMAGES) ? "Accept: text/html\r\n" : "")
// + "Accept: text/*\r\n"
+ (file.endsWith("robots.txt") ? "Connection: close\r\n" : "")
+ "Host: " + host + "\r\n" + "\r\n"/*
* + body
*/;
outStream.write(request.getBytes("US-ASCII"));
outStream.flush();
Try to send an OPTIONS request on the resource, needed request headers should be returned, some may be missing.

how to Redirect to another Action with json data in play-framework

I have the following code:
case class ResetPasswordJsonValidation (id : String ,email : String)
object ResetPasswordJsonValidation {
implicit val resetPasswordRead : Reads[ResetPasswordJsonValidation]= (
(JsPath \ "email").read(email) and
(JsPath \ "id").read(id)
)(ResetPasswordJsonValidation.apply _)
}
With the following Action:
def resetPassword = Action { request =>
request.body.asJson.get.validate[ResetPasswordJsonValidation].fold(
resetPassword => {
log.info("id is {}", resetPassword.id)
log.info("email id is {}", resetPassword.email)
}
)
}
And routes file:
POST /direct-user/reset-password controllers.DirectUserController.resetPassword
This is the curl file which I use to fire a request to the route above:
contentType="Content-type: application/json";
data='{ "id" : "54d3732d-d728-40d3-ae63-b18ab6be8e70" ,
"email":"bob#example.com"}';
echo " "
echo "------------------ Sending Data ------------------"
echo " "
echo "Content-Type : " $contentType
echo "Data : " $data
echo " "
echo "------------------ Response ------------------"
echo " "
echo " "
And the curl command:
curl --include --request POST --header "Content-type: application/json" --data "$data" http://localhost:9000//direct-user/reset-password
What I want to do is have another action that redirects to resetPassword, but keeping the body. How to do that?
Use flash scope
def A = Action {
var email:String="bob#example.com"
var id:String="54d3732d-d728-40d3-ae63-b18ab6be8e70"
Redirect(routes.DirectUserController.resetPassword()).flashing(
"email" -> email,
"id" -> id
)
}
The documentation: https://www.playframework.com/documentation/2.5.x/ScalaSessionFlash
You will need to write the special code to get variables from the flash scope, like
request.flash.get("email")

Does php urlencode the same with java urlencode?

In PHP:
php -r "echo urlencode('["IM"]'); "
The result is %5BIM%5D
But in java
String text = URLEncoder.encode('["IM"]',"UTF-8");
System.out.println("text" + text);
The result is text%5B%22IM%22%5D
What's the different between these two functions? How can I implement a java code to complete the same function of php?
String text = URLEncoder.encode('[IM]',"UTF-8");
System.out.println("text" + text);
gives %5BIM%5D
echo urlencode('["IM"]');
gives %5B%22IM%22%5D
echo urlencode('[IM]');
gives %5BIM%5D
echo urlencode('[\"IM\"]');
gives %5B%5C%22IM%5C%22%5D
php -r "echo urlencode('["IM"]'); "
The result is %5BIM%5D because the function urlencode is actually only taking the string [IM] as its input. while in java
String text = URLEncoder.encode('["IM"]',"UTF-8");
The string being passed is actually: ["IM"] which generates the value %22 which is encode-string for " the quote mark.
try to escape internal qoutes
php -r "echo urlencode('[\"IM\"]'); "

PHP email sent with confirmation link but confirmation link not working

I have an email being generated and sent in one file, a link in that email links to my confirmation page which then should move the users name around database tables according to choices they have made. Problem is i am getting nothing from the confirmation page at all, even when i use just a simple print statement and nothing else. I have been trying to figure it out but to no avail and error reporting is returning blank as well. here at the two files:
email.php (which fully works)
<?php
$link= mysql_connect(...............); //Establish connection to the MySQL server
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(.....);
$confirm = md5(uniqid(rand()));
$position = $_POST['position'];
$team_name = $_POST['team_name'];
$zip_code = $_POST['zip_code'];
$userId = $_POST['userId'];
$s=mysql_query("SELECT Coach, TeamId FROM TEAM WHERE TEAM.Name = '$team_name' AND TEAM.Zip ='$zip_code'") OR die ("Error 1"); //Get result from query
while($row=mysql_fetch_assoc($s))
{
$coachId = $row['Coach'];
$teamId = $row['TeamId'];
}
$l=mysql_query("SELECT Name, Email FROM USER WHERE USER.UserId = '$userId'") OR die ("Error 3"); //Get result from query
while($row = mysql_fetch_assoc($l))
{
$user_name = $row['Name'];
$user_email = $row['Email'];
}
$q=mysql_query("SELECT Name, Email FROM USER WHERE USER.UserId = '$coachId'") OR die ("Error 4"); //Get result from query
while($coach=mysql_fetch_assoc($q))
{
$to = $coach['Email'];
$name = $user_name;
$subject = "Scoutlet $position Request for The $team_name";
if($position == "Head Coach")
{
$message = "$name has requested to become the Head Coach for the $team_name.";
$message .= "\n\nClick on the following link to give $name permission to be the Head Coach of the $team_name (Located in the ZIP code $zip_code).\n\n";
$message .="Click Here to make $name the Head Coach";
}
else
{
$message = "$name has requested to become a Score Keeper for the $team_name.";
$message .= "\n\nClick on the following link to give $name permission to be a Score Keeper for the $team_name (Located in the ZIP code $zip_code).\n\n";
$message.="http://web.***.***/~***/confirmation.php?key=$confirm"; // way to prevent no spam, dont use txt
}
$headers = "From: ***";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$sent = mail($to, $subject, $message, $headers) ;
if($sent)
{
print "sent";
}
else
{
print "fail";
}
}
$sql=mysql_query("INSERT INTO CONFIRMATION(ConfirmationNumber, UserId, Email, TeamId, TeamName, Position)VALUES('$confirm', '$userId','$user_email','$teamId', '$team_name', '$position')") OR die ("Error 2"); //Get result from query
mysql_close();
?>
confirmation.php
<?
ini_set('display_errors',1);
error_reporting(E_ALL);
$confirm = $_GET['key'];
$link= mysql_connect(***********); //Establish connection to the MySQL server
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
echo "connect4e";
mysql_select_db(**********);
$sql1=mysql_query("SELECT * FROM CONFIRMATION WHERE ConfirmationNumber ='$confirm'") OR die ("Fail 1");
while($row=mysql_fetch_assoc($sql1))
{
$userId= $row['UserId'];
$user_email = $row['Email'];
$teamId = $row['TeamId'];
$team_name = $row['TeamName'];
$position= $row['Position'];
}
$sql2= mysql_query("INSERT INTO USER (Role) VALUES ('$position') WHERE UserId ='$userId'") OR die ("Fail 2");
if($position =="Head Coach")
{
$sql3= mysql_query("INSERT INTO TEAM (Coach) VALUES ('$userId') WHERE TeamId ='$teamId'") OR die ("Fail 3a");
}
else
{ // do a check earlier on to see if the user is already a score keeper for that team
$sql3= mysql_query("INSERT INTO SCOREKEEPS_FOR (ScoreKeeper, Team) VALUES ('$userId', '$teamId')") OR die ("Fail 3b");
}
$to= $user_email;
$subject="Welcome to Our Site";
$headers = "From: ******";
$message="Congratulations, you have been confirmed as a $position for The $team_name.";
$sent = mail($to,$subject,$message,$header);
if(sent)
{
$sql4=mysql_query("DELETE FROM CONFIRMATION WHERE ConfirmationNumber = '$confirm'") OR die ("Fail 5");
}
else
{
print "fail";
}
?>
I've already killed a ton of time just trying to error check which was a waste so hopefully more eyes will help solve it faster. any help or suggestions would be great. thanks in advance
if(sent) >>should be>> if($sent)
Could be your server only executes php with starting tag
<?php
instead of
<?
http://us2.php.net/manual/en/language.basic-syntax.phptags.php
PHP also allows for short tags (which are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option.
in your confirmation.php you're using short open tags <? ... ?>. Make sure your php short open tags is enable or simply use <?php ... ?> instead.

PHP - fsockopen() Connection timed out [duplicate]

I am working on a php file that connects to my game server and executes a command. The users enter their username on a HTML form that sends them and the username to a php file that connects to the server. The port is forwarded and the server is ready to receive the info, but I keep getting this error:
Warning: socket_connect() [function.socket-connect]: unable to connect [110]: Connection timed out in /home/moocraft/public_html/test/vote.php on line 8
error: could not connect to host
Here is the HTML file:
<html>
<body>
<form action="vote.php" method="post">
Minecraft Username: <input type="text" name="fname" />
<input type="submit" />
</form>
</body>
</html>
Here is the PHP file:
<?php
$HOST = "207.210.254.141"; //the ip of the bukkit server
$password = "examplepassword1";
$player = $_POST["fname"];
//Can't touch this:
$sock = socket_create(AF_INET, SOCK_STREAM, 0)
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, 4445)
or die("error: could not connect to host\n");
//Authentification
socket_write($sock, $command = md5($password)."<Password>", strlen($command) + 1)
or die("error: failed to write to socket\n");
//Begin custom code here.
socket_write($sock, $command = "/Command/ExecuteConsoleCommand:give $player 264 5;", strlen($command) + 1) //Writing text/command we want to send to the server
or die("error: failed to write to socket\n");
socket_write($sock, $command = "$player voted for MOOcraft and earned 5 diamonds. Vote at moocraft.org;", strlen($command) + 1)
or die("error: failed to write to socket\n");
?>
I can't figure out why I keep getting this. Any help is greatly appreciated.
Try something simple like:
$fp = fsockopen("207.210.254.141", 4445, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: 207.210.254.141\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
And see what do you get, it might be due to the reason that your server is taking too long to respond

Categories