Hello programmers around the world, I am currently working on my own browser game and I ran into a problem when trying to register an account and store the details into a database. I am currently using PHP in order to do it. When I enter the registration details username, email, password ...etc. and hit the register button nothing happens. The result should be that the values should be stored in a database and you should be redirected to another page.
Note I am using my own server which I made in Java the code is below:
package server.java;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
ServerSocket serversocket;
//entry point for our program
public static void main(String[] args) throws Exception {
new Main().runServer(); // to avoid any problems with static fields
}
public void runServer() throws Exception{
System.out.println("Server is started!");
serversocket = new ServerSocket(4567); //port number at which the server is running
//for accepting requests
acceptRequest();
}
private void acceptRequest() throws Exception{
while(true){ // we have to accept all the requests
//connection to the client is in the form of socket which contains the stream for input and output
Socket s = serversocket.accept();
ConnectionHandler ch = new ConnectionHandler(s);
//ch is the thread, so we have to strt the thread
ch.start();// this line of code will call the run() method automatically
}
}
}
package server.java;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
//this class basically handles all the connections which contain the requests
public class ConnectionHandler extends Thread{ //by extending to Thread, this class becoomes a Thread
Socket s;
//for sending the output to the client
PrintWriter pw;
//for getting the input from the client
BufferedReader br;
//constructor which accepts and uses a Socket
public ConnectionHandler(Socket s) throws Exception{
this.s = s;
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream());
}
/*
*Thread class contains a method run() which is called automatically when we start the thread
*in this method we have to read the request and give the responce
*/
public void run(){
try{
//here we get the request string and give this string to the HttpRequest class
String requestString = "";
//from br we have to read our request
//read until request is not of length 0 or br is ready
while(br.ready() || requestString.length() == 0){
requestString += (char) br.read();
}
System.out.println(requestString);// for testing purposes
HttpRequest request = new HttpRequest(requestString);
//now we pass the HttpRequest object to HttpResponce in order to get the responce
HttpResponce responce = new HttpResponce(request);
//write the final output to pw
pw.write(responce.responce.toCharArray());
pw.close();
br.close();
s.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
package server.java;
public class HttpRequest {
//first line contains 3 parts, 1 - request type, 2 - file name, 3 - http version
//for us only the file name is important
String filename;
//we have to create a constructor which accepts a string as input
public HttpRequest(String request){
//now we have the request from which only the fisrt line matters to us
String lines[] = request.split("\n");// now we have all the lines of the request separated
//this line basically splits the first line, and then selcets the second item which is our filename
filename = lines[0].split(" ")[1];
}
}
package server.java;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class HttpResponce {
HttpRequest request;
//this is the final responce which is generated
String responce;
//root path of the server
String root = "E:/root";
//we have to create a constructor which accepts a request as input
public HttpResponce(HttpRequest request) throws Exception{
this.request = request;
//now we have to open the file mentioned in request
File f = new File(root + this.request.filename);
try{
responce = "HTTP/1.1 200 \r\n"; //version of http and 200 for status code
//200 means everything is okay
responce += "Server: Our Java Server/1.0 \r\n"; //identity of the server
responce += "Content-Type: text/html \r\n"; //responce is in html format
responce += "Connection: close \r\n";//this line tells the browser to close the connection because no transmitions
responce += "Content-Length: " + f.length() + " \r\n"; //lngth of the responce file
responce += "\r\n"; //after blank line we have to append file data
//to read this file
FileInputStream fis = new FileInputStream(f);
int s;
while((s = fis.read()) != -1){ //-1 means end of file
responce += (char) s;
}
fis.close();
}catch(FileNotFoundException e){
//if we dont get a file then error 404
responce = responce.replace("200", "404");
}
catch(Exception e){
//if other error then 500 internal server error
responce = responce.replace("200", "500");
}
}
}
This is the entire code for my Java server.
Note: I think the server is working fine because it load and transitions between HTML pages. When it comes to PHP pages though it doesn't do anything so maybe it is the problem. I've been trying to solve this problem for two weeks now with no success so far? If somebody would be so kind as to help it would be really appreciated. Sending the code for the PHP page now:
<?php
session_start();
//connect to the database
$db = mysqli_connect("localhost", "root", "Smd497_497", "users");
if(isset($_POST['register'])){
$username = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$password2 = mysql_real_escape_string($_POST['password2']);
if($password == $password2){
//create user
$password = md5($password); //hash password before storing it for security purposes
$sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')";
mysqli_query($db, $sql);
$_SESSION['message'] = "Registration successful!";
header('Location: choice.php'); //redirect to the next page
else{
//failed to create user
$_SESSION['message'] = "The passwords DO NOT match!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Registration page</title>
<style type="text/css">
body{
background-position: top;
background-repeat: no-repeat;
background-size: cover;
}
.starwars{
margin-left: 525px;
}
.blyat{
position: relative;
text-align; center;
margin-left: 325px;
}
.registration{
position: absolute;
top: 80px;
left: 22%;
font-size: 30px;
border-bottom: 1px solid black;
padding-bottom: 5px;
}
.details{
position: absolute;
top: 130px;
left: 14%;
}
form {
margin-left: 100px;
}
</style>
</head>
<body background = "https://pre00.deviantart.net/c83b/th/pre/i/2013/067/0/1/star_wars_sith_or_jedi_by_misterrecord-d5xdgdq.png">
<div class = "starwars">
<img src = "https://novaopenstore.com/Image/EventContainerImage/30" height = "100" width = "300" />
</div>
<div class = "blyat">
<img src = "https://scontent-lht6-1.xx.fbcdn.net/v/t1.0-9/30629292_1627559157293346_4622477325102925006_n.jpg?_nc_cat=0&oh=82718a4b31b952272b36d8a374a0ae14&oe=5B712921" height = "425" width = "700"/>
<div class = "registration"><b>Registration Details</b></div>
<div class = "details">
<form class="form" action="register.php" method="post">
<div class="alert-error"><?= $_SESSION['message'] ?></div>
Choose you battlefield!<br>
Battlefield: <select>
<option value="Battlefield 1">Battlefield 1</option>
</select><br>
Choose your name!<br>
Username: <input type="text" name="username" required /><br>
Choose your email!<br>
Email: <input type="text" name = "email" required /><br>
Choose your password!<br>
Password: <input type="password" name="password" required/><br>
Confirm your password!<br>
Confirm Password: <input type="password" name="password2" required/><br>
<input type="submit" value="Register" name="register" class="btn btn-block btn-primary"/>
</form>
</div>
</div>
</body>
</html>
Note: I am currently not having any problems with HTML or CSS (at least not any I know of...) Another useful thing to say is that some of you might think that my server is not working or that it is not receiving the information. Last time I tried I got the following result:
**username=zexstoi&email=ss%40mail.bg&password=147852369&password2=147852369®ister=Register
**
This is evidence that the server is receiveing the right info just not processing it right for some reason could be the server or the PHP page.As said above if anybody has any idea for a fix please share it with me and the rest of the community. Have a nice day everybody!
Related
I want to write code for login to websites with java.
Here is the code :
package login;
import java.net.*;
import java.io.*;
public class ConnectToURL {
// Variables to hold the URL object and its connection to that URL.
private static URL URLObj;
private static URLConnection connect;
public static void main(String[] args) {
try {
CookieManager cManager = new CookieManager();
CookieHandler.setDefault(cManager);
// Establish a URL and open a connection to it. Set it to output mode.
URLObj = new URL("https://accounts.google.com/ServiceLogin?service=mail&continue=https://mail.google.com/mail/#identifier");
connect = URLObj.openConnection();
connect.setDoOutput(true);
}
catch (MalformedURLException ex) {
System.out.println("The URL specified was unable to be parsed or uses an invalid protocol. Please try again.");
System.exit(1);
}
catch (Exception ex) {
System.out.println("An exception occurred. " + ex.getMessage());
System.exit(1);
}
try {
// Create a buffered writer to the URLConnection's output stream and write our forms parameters.
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream()));
writer.write("Email=myemail#gmail.Com&Passwd=123456&submit=Login");
writer.close();
// Now establish a buffered reader to read the URLConnection's input stream.
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String lineRead = "";
// Read all available lines of data from the URL and print them to screen.
while ((lineRead = reader.readLine()) != null) {
System.out.println(lineRead);
}
reader.close();
}
catch (Exception ex) {
System.out.println("There was an error reading or writing to the URL: " + ex.getMessage());
}
}
}
I have tried this code on Facebook and Gmail but the problem is that it didn't work.
It keep telling me that the cookies is not enabled. (I have used chrome browser and they were enabled).
Is there any other ways to achieve this?
If your goal is just login to some web site, much better solution is to use Selenium Web Driver.
It has API for creating modern drivers instances, and operate with their web elements.
Code example:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class Example {
public static void main(String[] args) {
// Create a new instance of the html unit driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new HtmlUnitDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
Also it has solution how to manage cookies as well - Cookies
Just look at documentation how to configure driver instances and manage web elements, preferred way is to use Page Object pattern.
Update:
For getting location from web page which doesn't have id or name attributes can be done using xpath expressions, very useful for this can be firefox extensions like:
FirePath
XpathChecker.
And use concisely and short Xpath functions.
For example:
<table>
<tr>
<td>
<p>some text here 1</p>
</td>
</tr>
<tr>
<td>
<p>some text here 2</p>
</td>
</tr>
<tr>
<td>
<p>some text here 3</p>
</td>
</tr>
</table>
for getting text some text here 2 you able to use following xpath:
//tr[2]/td/p
if you know that text is static you able to use contains():
//p[contains(text(), 'some text here 2')]
For checking if your xpath is unique at this page the best is to use console.
How to do is described here How to verify an XPath expression
What exactly are you trying to do with this? You are almost certainly better off using something like Selenium web-driver for browser automation tasks, as you piggy back on the work of an existing web-browser to handle things like cookies.
In this case, you're talking about your web browser saying cookies are not enabled, but you're not actually using a web browser, you're sending a connection via your java application.
I play NanoHTTPD and WebServer based on it. To update any object in my code (application) I can use GET/POST method. But how can I create dynamic pages? For example I have html page on disc and it should present current temperature:
<html>
<head>
<title>My page</title>
</head>
<body>
<p style="text-align: center">Temperature: [temperature variable] </p>
</body>
</html>
How can I pass "variable temperature" from my application based on NanoHTTPD to html file and present it in browser?
You have to read the template from your disk, and replace the [temperature variable] substring with the value you want to include.
To read the file, you can use the Files class:
byte[] data = Files.readAllBytes(Paths.get("mytemplpate.html"));
String templ = new String(data, StandardCharsets.UTF_8);
To insert your temperature:
double temperature = 22.3;
String html = templ.replace("[temperature variable]", Double.toString(temperature));
And finally to send this as the response with NanoHTTPD:
return new NanoHTTPD.Response(html);
The complete program:
Foreword: Exceptions are not handled, this is just for demonstration purposes.
public class TemperatureServer extends NanoHTTPD {
// Loaded and cached html template
private static String templ;
// Value of this variable will be included and sent in the response
private static double temperature;
public TemperatureServer () {
super(8080);
}
#Override
public Response serve(IHTTPSession session) {
String html = templ.replace("[temperature variable]",
Double.toString(temperature));
return new NanoHTTPD.Response(html);
}
public static void main(String[] args) throws Exception {
byte[] data = Files.readAllBytes(Paths.get("mytemplpate.html"));
templ = new String(data, StandardCharsets.UTF_8);
ServerRunner.run(TemperatureServer.class);
}
}
For more advanced examples check out the Samples package of the NanoHttpd Github site.
I'm trying to write sample file from applet but is not working. Below is the code.
Applet
public class PasteImageApplet extends JApplet {
Clipboard clipboard;
Toolkit toolkit;
JLabel lbl;
public String getClipboardImageURL(String server) {
lbl.setText("pasting image");
String url = "";
try {
DataFlavor dataFlavor = DataFlavor.imageFlavor;
System.out.println(dataFlavor.getDefaultRepresentationClass());
Object object = null;
try {
object = clipboard.getContents(null)
.getTransferData(dataFlavor);
JOptionPane.showMessageDialog(null,"Image found.");
try
{
Writer output = null;
String text = "Test Write File";
File file = new File("write.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Error writing file"+ex);
return "" ;
}
//return "";
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "No image found.");
return "";
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error."+e);
return "";
}
return url;
}
public void init() {
lbl = new JLabel("");
lbl.setText("applet started");
add(lbl);
toolkit = Toolkit.getDefaultToolkit();
clipboard = toolkit.getSystemClipboard();
}
}
HTML
<html>
<head>
<title>Clipboard image demo</title>
<script type="text/javascript">
function loadApplet() {
// Deferred load to display text first
document.getElementById("applet").innerHTML = '<object id="paste-image" classid="java:PasteImageApplet.class" type="application/x-java-applet" archive="tst.jar" width="1" height="1"></object>';
}
function getImage() {
obj = document.getElementById('paste-image');
postTo = "http://localhost/PasteImageApplet/PasteImageApplet/Web/shoot.php"; // Change this to your URL
image = obj.getClipboardImageURL(postTo);
if (image) {
url = "shots/" + image;
document.getElementById("target").src = url;
document.getElementById("url").value = document.getElementById("target").src; // to get full path, hack, I know ;)
document.getElementById("container").style.display = "";
}
}
</script>
<body onload="loadApplet();">
<p>
Copy some image data to your clipboard, accept the applet (it only accesses the clipboard) and click the button :-)
See a blog post about this demo
</p>
<p>
<div id="applet"></div>
<input type="button" value="Paste it!" onclick="getImage();">
</p>
<div id="container" style="display: none;">
<input type="text" id="url" style="width: 700px;"><br />
<iframe id="target" width="700" height="400"></iframe>
</div>
</body>
</html>
I didn't get any error as well. Please advice.
That's because applets live there own sandbox, where they require special permission to perform certain operations, like read or write the disk of a client machine. Remember, applets execute within the context of the client machine, they are guests and need to follow the house rules
Check out What Applets can and cannot do for more details
An applet cannot establish a File on the server. That is not how servers work. If a server accepts uploads, it must provide specific functionality to enable that and the applet must use that functionality.
As long as the functionality to accept an upload is on the same server, the applet can remain sand-boxed.
you can see the console for applets via the (windows) taskbar, you right click the java icon(when applet is running it should appear on the lower right) and right click > open console, you can debug there, this is where the stack trace of an applet goes.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to upload a file using Java HttpClient library working with PHP - strange problem
I'm trying to create a script that can automatically submit a form on a website with two fields: title and description and a file input where I should upload an image.
The last days I've searched every page I found on google but I can't solve my problem...
I also need to post a cookie, I've made the cookie using:
connection.setRequestProperty("Cookie", cookie); //this worked
But I have problems submitting the form, first I'we tried using HttpUrlConnection, but I was unable to figure it out, now I'm trying to solve my problem using HttpClient
The html form looks like this:
<form action="submit.php" method="post" enctype="multipart/form-data">
<input type="text" name="title">
<input name="biguploadimage" type="file">
<textarea name="description"></textarea>
<input type="image" src="/images/submit-button.png">
</form>
My image is located at d:/images/x.gif
Please provide me a full code because I'm new to java.
O, and how to create the cookie using HttpClient ?
Thanks a lot in advice!
This url might help you to solve your problem. It's not that straightforward otherwise I would have pasted the code here. upload files in java
You could also look at this question here
similar question on stackoverflow
There is good article with code examples: http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload
Pay attention to MultipartPostMethod. This will allow you to post file and another data in one request.
How to do simple POST with many parameters described there: http://hc.apache.org/httpclient-3.x/methods/post.html
I recently did this using Spring Web MVC and Apache Commons FileUpload:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
(...)
#RequestMapping(method = RequestMethod.POST)
public ModelAndView uploadFile(HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView("view");
if (ServletFileUpload.isMultipartContent(request)) {
handleMultiPartContent(request);
}
return modelAndView;
}
private void handleMultiPartContent(HttpServletRequest request) {
ServletFileUpload upload = new ServletFileUpload();
upload.setFileSizeMax(2097152); // 2 Mb
try {
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
if (!item.isFormField()) {
File tempFile = saveFile(item);
// process the file
}
}
}
catch (FileUploadException e) {
LOG.debug("Error uploading file", e);
}
catch (IOException e) {
LOG.debug("Error uploading file", e);
}
}
private File saveFile(FileItemStream item) {
InputStream in = null;
OutputStream out = null;
try {
in = item.openStream();
File tmpFile = File.createTempFile("tmp_upload", null);
tmpFile.deleteOnExit();
out = new FileOutputStream(tmpFile);
long bytes = 0;
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
bytes += len;
}
LOG.debug(String.format("Saved %s bytes to %s ", bytes, tmpFile.getCanonicalPath()));
return tmpFile;
}
catch (IOException e) {
LOG.debug("Could not save file", e);
Throwable cause = e.getCause();
if (cause instanceof FileSizeLimitExceededException) {
LOG.debug("File too large", e);
}
else {
LOG.debug("Technical error", e);
}
return null;
}
finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
catch (IOException e) {
LOG.debug("Could not close stream", e);
}
}
}
This saves the uploaded file to a temp file.
If you don't need all the low-level control over the upload, it is much simpler to use the CommonsMultipartResolver:
<!-- Configure the multipart resolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2097152"/>
</bean>
An example form in the jsp:
<form:form modelAttribute="myForm" method="post" enctype="multipart/form-data">
<form:input path="bean.uploadedFile" type="file"/>
</form>
The uploadedDocument in the bean is of the type org.springframework.web.multipart.CommonsMultipartFile and can be accessed direcly in the controller (the multipartResolver automatically parses every multipart-request)
I've been trying to access a website to parse data for an Android application I am developing, but I am having no luck when it comes to logging in.
The website is https://giffgaff.com/mobile/login
And below is a stripped out version of the form from that page (HTML):
<form action="/mobile/login" method="post">
<input type="hidden" name="login_security_token" value="b22155c7259f402f8e005a771c460670">
<input type="hidden" name="redirect" value="/mobile">
<input type="hidden" name="p_next_page" value="">
<input name="nickname" maxlength="25" type="text" value="" />
<input name="password" type="password" value="" />
<button name="step" type="submit" value="Login">Login</button>
</form>
Can anyone please suggest how I can login to this website using Java then parse the redirected page?
Up to now, I've tried processes on the lines of:
public static void main(Context context) {
try {
// Construct data
String data = URLEncoder.encode("nickname", "UTF-8") + "=" + URLEncoder.encode("testingA", "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode("testing", "UTF-8");
// Send data
URL url = new URL("https://giffgaff.com/mobile/login");
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 str = "";
String line;
while ((line = rd.readLine()) != null) {
str += line;
}
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Output");
alertDialog.setMessage(str);
alertDialog.setButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
wr.close();
rd.close();
} catch (Exception e) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("ERROR");
alertDialog.setMessage(e.toString());
alertDialog.setButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
But my attempts return the page as if the login information was incorrect.
If you would like to see for yourself how the login page behaves, here's some test login details:
Nickname (username): testingA
Password: testing
The site also seems to depend on a Cookie called "napaSessionId"
First a word of caution, if you don't have direct permission to do this, beware, the site in question may preclude this in their terms of service.
To answer the question, there are many, many reasons a site would reject a login. To do this successfully you need to get as close as possible to how a browser would handle the transaction. To do that you need to see what a real browser is doing.
https is more tricky as many http sniffers can't deal with it but httpwatch claims it can. Check out the HTTP transactions and then try to replicate them.
Your url.openConnection() call will actually return an instance of HTTPURLConnction, cast to that & then you'll be able to easily set various http headers such as the User-Agent.
A final note, you say a cookie may be required. Your code isn't going to deal with cookies. To do that you'll need to use a cookie manager, e.g.: http://download.oracle.com/javase/tutorial/networking/cookies/index.html
You might want to check out Jsoup, htmlUnit and httpUnit. I'm trying this right now and am confronted with all kinds of difficulties, but I'm sure one of those projects is the way to go...
Good luck, keep me posted!