Display captcha in Jframe - java

I want to create application for registration in Java, then I want to submit the information to a website. This is only experiment so the information for the registration(e.g username, password) will be submit with GET request. However I want to integrate captcha with the registration and I want to display it on the Jframe and submit the answer along side with the other data. I have no idea how to get the captcha image, and then submit the data. Also I think to use the new reCaptcha(where it ask you to select foods). Any ideas how to do this?
Edit:
I know how to display the image with JLabel, I also was able to find a way to extract it Get image for captcha session .Now i'm wondering how to send the response.

To send a response you will probably need a Session ID from the server and the clients answer then just send a GET request to the server with both of the values
public void getMethod() throws IOException
{
String userAgent = "Java/" + Runtime.class.getPackage().getImplementationVersion();
//The server will need to know what "question" we are answering so it sent us the captha and a sesion ID
//example is just a random one you will need to figure out how to get a sesion id
String captchaSesionParam = "captchaSesionID=";
String captchaSesionID = UUID.randomUUID().toString();
//user has completed captha client side here is their answer
String queryParam = "answer=";
String answer = "blah blah answer";
String urlString = "https://127.0.0.1/?" + queryParam + URLEncoder.encode(answer, "UTF-8") + "&" + captchaSesionParam + URLEncoder.encode(captchaSesionID, "UTF-8");
URL url = new URL(urlString);
//Open a HTTPS connection to the URL
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//set request method to GET
con.setRequestMethod("GET");
//set user agent to our agent (by default I believe that this is 'Java/Version')
con.setRequestProperty("User-Agent", userAgent);
//print out debug info about request method and url
System.out.println(con.getRequestMethod() + " URL : " + url);
int responseCode = con.getResponseCode();
System.out.println("Server response code: " + responseCode);
try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));)
{
String line;
List<String> lines = new ArrayList<String>();
while ((line = in.readLine()) != null)
{
lines.add(line);
}
//parse lines received from server to see if the captcha was (in)correct
//print lines for debug
for(String l : lines)
{
System.out.println(l);
}
}
}

Related

How to Close HttpsURLConnection Java

I am trying to request data from the server using HttpsURLConnection; I currently have the server requiring the user to enter a username and password via a prompt. In a web browser after you enter the correct username and password, the browser would save the username and password as a session cookie in your browser so you can visit other pages within site without being prompted for your credentials. But for the client which is in Java, it does not save the username and password. I am trying to use .disconnect() to close the connection, but I keep getting the following error:
java.lang.IllegalStateException: Already connected
at sun.net.www.protocol.http.HttpURLConnection.setRequestProperty(HttpURLConnection.java:3053)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.setRequestProperty(HttpsURLConnectionImpl.java:316)
My Java Code:
private static void sendPost(String _url) throws Exception {
String url = _url;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
int responseCode = con.getResponseCode();
Auth(con);
if (responseCode == 200) {
label.setText("Sucssesfully Scanned: " + StudID.getText());
} else {
label.setText("Error, please scan again");
}
con.disconnect();
}
private static ArrayList<String> Get(String _url) throws Exception {
ArrayList<String> list = new ArrayList<>();
JsonParser parser = new JsonParser();
String url = _url;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Auth(con);
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
con.disconnect();
JsonElement element = parser.parse(response.toString());
if (element.isJsonObject()) {
JsonObject data = element.getAsJsonObject();
for (int i = 0; i < data.get("chapels").getAsJsonArray().size(); i++) {
JsonObject jObj = (JsonObject) data.get("chapels").getAsJsonArray().get(i);
list.add(jObj.get("Name").toString().replaceAll("\"", "") + " - " + jObj.get("Loc").toString().replaceAll("\"", ""));
}
}
return (list);
}
private static void Auth(HttpsURLConnection con){
String encodedBytes = Base64.getEncoder().encodeToString((BCrypt.hashpw("swheeler17", BCrypt.gensalt(10)) + ":" + BCrypt.hashpw("Trinity", BCrypt.gensalt(10))).getBytes());
con.setRequestProperty("authorization", "Basic " + encodedBytes);
}
Example of username and password prompt: https://chapel-logs.herokuapp.com/chapel
java.lang.IllegalStateException: Already connected
That exception means that you have attempted to set the property giving the authorization for the request after it has been sent.
This is probably where it happens:
int responseCode = con.getResponseCode();
Auth(con);
and Auth calls setRequestProperty.
Asking for the response code causes the request to be sent if if hasn't already been sent. (Obviously ... you can't get the response code until you get the response, and the server can't give you one unless the request is sent.)
To answer your question, calling disconnect on the connection will disconnect the connection.
But that's not what is causing your problem. The stacktrace shows clearly that the exception is happening when something is calling setRequestProperty.
Based off of Stephen C's answer I determined the swap the order of:
int responseCode = con.getResponseCode();
Auth(con);
So the working solution is:
Auth(con);
int responseCode = con.getResponseCode();
I'm assuming ResponseCode() creates a request to the server if a request has not already been made, otherwise ResponseCode() uses the pre-existing request. Upon further testing, I concluded there is no need to call .disconnect().

Java alternative for curl -T

i must send one text string using java to a IP web cam, before it take picture. So after I read the camera user manual and searched in google, the only thing i found was using cURL. I install it and its run fine, and everything is okay, the text from the file appear in the video streaming. The command is this
curl -T test.xml http://admin:pass#192.168.0.1/Video/inputs/channels/2/overlays/text/2
and the content of test.xml is:
<TextOverlay xmlns="http://www.hikvision.com/ver10/XMLSchema" version="1.0">
<id>2</id>
<enabled>true</enabled>
<posX>5</posX>
<posY>5</posY>
<message>Text here </message>
</TextOverlay>
So I want to send this content using Java, I already tried using post and java.net but I get an error "Server returned HTTP response code: 403 for URL"
Here is my code:
System.out.println("Starting......");
URL url = new URL("http://192.168.0.1/Video/inputs/channels/2/overlays/text/2/");
String data = "<TextOverlay xmlns=\"http://www.hikvision.com/ver10/XMLSchema\" version=\"1.0\">\n"
+ "<id>2</id>\n"
+ "<enabled>true</enabled>\n"
+ "<posX>5</posX>\n"
+ "<posY>5</posY>\n"
+ "<message>Text here</message>\n"
+ "</TextOverlay>";
HttpURLConnection httpConnection = prepareConn(url, null, "admin", "pass");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty ( "Content-Type", "text/xml" );
OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
out.write(data);
out.flush();
out.close();
System.out.println("Printing......");
System.out.println(httpConnection.getResponseCode());
System.out.println(httpConnection.getResponseMessage());
InputStreamReader reader = new InputStreamReader(httpConnection.getInputStream());
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[2048];
int num;
while(-1 != (num = reader.read(cbuf)))
{
buf.append(cbuf, 0, num);
}
String result = buf.toString();
System.out.println("\nResponse received from server after POST" + result);
}
static private HttpURLConnection prepareConn(final URL url, Properties request_props, String username, String password) throws Error, IOException
{
System.out.println("Authorization......");
if (!url.getProtocol().equalsIgnoreCase("http"))
throw new Error(url.toString() + " is not HTTP!");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(300);
conn.setRequestMethod("POST");
final Properties DEFAULT_REQUEST_PROPS = new Properties();
DEFAULT_REQUEST_PROPS.setProperty("charset", "utf-8");
final Properties props = new Properties(DEFAULT_REQUEST_PROPS);
if (request_props != null)
for (final String name : request_props.stringPropertyNames())
props.setProperty(name, request_props.getProperty(name));
for (final String name : props.stringPropertyNames())
conn.setRequestProperty(name, props.getProperty(name));
if(null != username && null != password)
conn.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode((username+":"+password).getBytes()));
return conn;
}
Hope someone can help :)
All the best !
I just use wrong RequestMethod, after deep research I found that i must use PUT not POST request. Now just change setRequestMethod("POST") to setRequestMethod("PUT") and works like a charm.

Difference between Java Post Request and browser post request

I am trying to use api of one popular russian social networks. I am using OAuth via Java HttpUrlConnection. The problem is, when I send post data via Java, I get 401 response code. When I copy request and paste it browser, I get redirect to URL containing access token I need. That means that my post request is correct, but why when I send it with Java I get 401 error? When I send request with incorrect password, I get 200. It means that request is correct too.
private void getHomeAuth() throws Exception {
String url = "https://oauth.vk.com/authorize?client_id=APP_ID&scope=friends&redirect_uri=https://oauth.vk.com/blank.html&display=page&v=5.34&response_type=token";
URL oauth = new URL(url);
HttpURLConnection connection = (HttpURLConnection) oauth.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = connection.getResponseCode();
System.out.println("Response code: " + responseCode);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while((inputLine = reader.readLine()) != null)
response.append(inputLine + "\n");
reader.close();
PrintWriter writer = new PrintWriter("auth.html");
writer.print(response);
writer.close();
parse();
cookies = connection.getHeaderField("Set-Cookie");
referer = connection.getURL().toString();
}
private void postAuth() throws Exception {
email = URLEncoder.encode("example#gmail.com", "UTF-8");
password = "password";
_origin = URLEncoder.encode(_origin, "UTF-8");
String url = "https://login.vk.com/?act=login&soft=1";
URL post = new URL(url);
String urlParameters = "ip_h=" + ip_h + "&_origin=" + _origin + "&to=" + to + "&expire=" + expire + "&email=" + email + "&pass=" + password;
HttpsURLConnection con = (HttpsURLConnection) post.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Cookie", cookies);
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Sent post. Response code: " + responseCode + "\nRequest: " + post.toString() + urlParameters + "\nRequestMethod: " + con.getRequestMethod());
}
I also tryied to send this request via addon in browser, and the result was correct. I obtained access token from redirect link.
Maybe the problem is that something inside request is incorrect. I have tried to monitor requests from java app, but I failed.
My experience with this kind of problem is that the http request that first authenticates the user also puts cookies (scope varies from case to case) into the response and subsequent http requests are expected to contain those cookies. Look very closely at the complete returned response headers to see what cookies might have been returned.

Passing value from applet to PHP

I want to send values of two variables to a PHP file from a Java applet), and I tried the following code.
try {
URL url = new URL(getCodeBase(),"abc.php");
URLConnection con = url.openConnection();
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
ps.print("score="+score);
ps.print("username="+username);
con.getInputStream();
ps.close();
} catch (Exception e) {
g.drawString(""+e, 200,100);
}
I got the following error:
java.net.UnknownServiceException:protocol doesn't support output
java.net.UnknownServiceException:protocol doesn't support output
Means that you are using a protocol that doesn't support output.
getCodeBase() refers to a file url, so something like
file:/path/to/the/applet
The protocol is file, which doesn't support outout. You are looking for a http protocol, which supports output.
Maybe you wanted getDocumentBase(), which actually returns the web page where the applet is, i.e.
http://www.path.to/the/applet
Here's some code I used with my own applet, to send values (via POST) to a PHP script on my server:
I would use it like this:
String content = "";
content = content + "a=update&gid=" + gid + "&map=" + getMapString();
content = content + "&left_to_deploy=" + leftToDeploy + "&playerColor=" + playerColor;
content = content + "&uid=" + uid + "&player_won=" + didWin;
content = content + "&last_action=" + lastActionCode + "&appletID=" + appletID;
String result = "";
try {
result = requestFromDB(content);
System.out.println("Sending - " + content);
} catch (Exception e) {
status = e.toString();
}
As you can see, I am adding up all my values to send into a "content" string, then calling my requestFromDB method (which posts my "request" values, and returns the server's response) :
public String requestFromDB(String request) throws Exception
{
// This will accept a formatted request string, send it to the
// PHP script, then collect the response and return it as a String.
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
// URL of CGI-Bin script.
url = new URL ("http://" + siteRoot + "/globalconquest/applet-update.php");
// URL connection channel.
urlConn = url.openConnection();
// Let the run-time system (RTS) know that we want input.
urlConn.setDoInput (true);
// Let the RTS know that we want to do output.
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
// Specify the content type.
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Send POST output.
printout = new DataOutputStream (urlConn.getOutputStream ());
printout.writeBytes (request);
printout.flush ();
printout.close ();
// Get response data.
input = new DataInputStream (urlConn.getInputStream ());
String str;
String a = "";
while (null != ((str = input.readLine())))
{
a = a + str;
}
input.close ();
System.out.println("Got " + a);
if (a.trim().equals("1")) {
// Error!
mode = "error";
}
return a;
} // requestFromDB
In my PHP script, I would only need to look at $_POST for my values. Then I would just print a response.
Note! Your PHP script MUST be on the same server as the applet for security reasons, or this will not work.

Java Cookie/Session - Problem - phpmyadmin

hi guys i want to code a tool, which interacts with phpmyadmin. I want to create a new Table. For this i need the cookie and the security token. Both things I've done. My Problem is i'll take the cookies and open an new URLConnection with these Cookies. And take the token to validate my request. But everytime i do this i got the response that my SQLQuery is empty and if u get this Error ur token is invalid. And an invalid token means that ur cookies haven't been placed very well in the new connection so u don't have the same session as before. What i've done wrong, any idea to fix this problem?
Here is my code:(its very ugly but its only for testing purposes)
import java.io.*;
import java.net.*;
import java.util.List;
public class connect {
public void connectto() throws IOException{
URLConnection connection = new URL("http://localhost/phpmyadmin/index.php").openConnection();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
connection.connect();
InputStream response = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(response));
String line;
String token = "";
while((line = br.readLine())!= null){
System.out.println(line);
if (line.contains("var token = ")){
System.out.println("hit");
token = "&token=" + line.substring(line.indexOf("var token = '") + "var token = '".length()).substring(0, line.substring(line.indexOf("var token = '") + "var token = '".length()).indexOf("';"));
}
}
System.out.println(token);
String url = URLEncoder.encode("db=mysql&sql_query=CREATE TABLE testtable(testtable TEXT);" + token, "UTF-8");
connection = new URL("http://localhost/phpmyadmin/sql.php?" + url).openConnection();
connection.setDoOutput(true);
for (String cookie : cookies) {
System.out.println(cookie.split(";", 2)[0]);
connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}
connection.connect();
response = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(response));
line = "";
while((line = br.readLine())!= null){
System.out.println(line);
}
}
}
My apologies if I misunderstood your issue but why are you forcing the request through phpMyAdmin? The point of phpMyAdmin is to provide a UI to people to work with their MySQL database. If you want to interact with the MySQL database you should be opening a connection directly to the database and executing statements in the java code.
Again, please excuse my ignorance if this is unfeasable for you but if you must work through phpMyAdmin instead of a direct connection between Java and your DB please provide more information.

Categories