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.
Related
I am trying to build a Java code to create users in AAD using MSAL and MS Graph API. Below is the code that I am using to create the user. I am able to retrieve the token successfully, however getting exception while trying to POST the request. What am I doing wrong?
public static void main(String[] args) throws Exception {
Map<String,Object> params = new LinkedHashMap<>();
params.put("givenName", "Test");
params.put("displayName", "ABC");
params.put("accountEnabled", true);
params.put("mailNickname","abc");
params.put("userPrincipalName","jcooper#demo.onmicrosoft.com");
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
int length =postDataBytes.length;
URL url = new URL("https://graph.microsoft.com/v1.0/users");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/json");
conn.setRequestProperty("Authorization", "Bearer "+accessToken);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestProperty("Content-Length",Integer.toString(length));
conn.connect();
conn.getInputStream();
try (var wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postDataBytes);
}
StringBuilder content;
System.out.println(postDataBytes+" "+postData);
try (var br = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
String line;
content = new StringBuilder();
while ((line = br.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
}
System.out.println(content.toString());
}
Exception : Exception in thread "main" java.io.IOException: Server returned HTTP response code: 411 for URL: https://graph.microsoft.com/v1.0/users
According to some test, I met the same issue with yours. It seems the code is correct but do not know why it still show 411 error. It may be caused by the graph api can just accept json request body but you convert the request body to application/x-www-form-urlencoded in your first part of code(I'm not sure because I test the code with json request body but still show 411).
Since you mentioned use MSAL to get access token, you can also continue to use MSAL to create the user. Please refer to this example:
GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();
User user = new User();
user.accountEnabled = true;
user.displayName = "Adele Vance";
user.mailNickname = "AdeleV";
user.userPrincipalName = "AdeleV#contoso.onmicrosoft.com";
PasswordProfile passwordProfile = new PasswordProfile();
passwordProfile.forceChangePasswordNextSignIn = true;
passwordProfile.password = "xWwvJ]6NMw+bWH-d";
user.passwordProfile = passwordProfile;
graphClient.users()
.buildRequest()
.post(user);
For accessing Microsoft Graph from a desktop app, I'd use the InteractiveBrowserCredentialBuilder() with the TokenCredentialAuthProvider that comes with GraphSDK to get the Graph token. Check out the great sample code here. All you'd need to do to customize this is to change the last line and set the scopes differently based on what Graph API you need to call. There's a link on the bottom of that page that'll teach you to register your app properly.
The simplest way in a web app is to use Azure AD Spring Boot Starter to get an access token for a logged-in user, and use GraphSDK to call Graph in a Spring 5 web app. See this sample that demonstrates this along with full instructions (Relevant Graph code is is in SampleController.java and Utilities.java)
Can u please help me to understand with simple piece of java code to get connect wth qc 12 using rest api.
I gone thorough the rest api documentation but am not clear with how to start with.but it will be helpful if people can show me a simple java code for authentication(login,logout or getting defect details) using rest api. Also want to know do i need to include any jars in my build path.
Thanks a lot friends.
I don't quite get what you're asking, but if you want to connect to a REST API, there are several ways... I usually use HttpURLConnection, here's an example of a get:
public String getProfile(String URL) throws IOException {
URL getURL = new URL(url);
//Establish a https connection with that URL.
HttpURLConnection con = (HttpURLConnection) getURL.openConnection();
//Select the request method, in this case GET.
con.setRequestMethod("GET");
//Add the request headers.
con.setRequestProperty("header", headerValue);
System.out.println("\nSending 'GET' request to URL : " + url);
int responseCode;
try {
responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
} catch (Exception e) {
System.out.println("Error: Connection problem.");
}
InputStreamReader isr = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = br.readLine()) != null) {
//Save the response.
response.append(inputLine + '\n');
}
br.close();
return response.toString();
}
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);
}
}
}
I want to send datas from my Java program to a Tine2.0 server. I have found a solution called JSON-RPC for Java, working on the Post http method.
I have already created a class doing a Post request to a test page of the server, this is the code:
import java.io.*;
import java.net.*;
public class EnvoiEnBaseViaURL {
public static void main(String[] args) throws Exception {
String tacheSent = URLEncoder.encode(args[0], "UTF-8"); //args[0] = "tache a envoyer"
String noteSent = URLEncoder.encode(args[1], "UTF-8"); //args[1] = "note a envoyer"
String dossier = URLEncoder.encode(args[2], "UTF-8"); //args[2] = "dossier a envoyer"
String context = URLEncoder.encode(args[3], "UTF-8"); //args[3] = "contexte a envoyer"
String iD = URLEncoder.encode(args[4], "UTF-8");
String pass = URLEncoder.encode(args[5], "UTF-8");
URL url = new URL(args[6]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write("TacheEnvoyee=" + tacheSent + "&NoteEnvoyee=" + noteSent + "&Dossier=" + dossier + "&Contexte=" + context + "&Identifiant=" + iD + "&Password=" + pass);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}
It works, I successfully send datas to this page and it returns me what I have sent. But now I work with the Tine2.0 server, I have to use authentication to connect.
I have tried to follow this tutorial: https://github.com/briandilley/jsonrpc4j, I have dowloaded the ZIP file but I dont know what am I supposed to do with, Where I have to send it...(the tutorial don't explain it at all...) At the moment, the Useron the public Interface UserServicedoesn't exist, etc...
I think I can do what I want to just with
JsonRpcHttpClient client = new JsonRpcHttpClient(
new URL("http://example.com/UserService.json"));
User user = client.invoke("createUser", new Object[] { "bob", "the builder" }, User.class);
But Java, obviously, as said previously, don't recognize JsonRpcHttpClient or User..
If anyone already worked with JSON-RPC and and can explain me what am I supposed to do, maybe install or add to the Java Build Path?
I hope i'm enough concise, don't hesitate to ask informations is some are missing.
Thank you.
I want to do an online xml request in java but the server responds with 401 error that means that there is an authentication that is need to access the server. I have the certfile.cer that i can use to do the authentication but i dont know how to load it in java.How can I achieve this in java? Here is part of my code.
StringBuilder answer = new StringBuilder();
URL url = new URL("www.myurl.com");
URLConnection conn = url.openConnection();
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(xml);
writer.flush();
String line;
while ((line = reader.readLine()) != null)
{
answer.append(line);
}