I just started working with JHipster and I created a .jh file with the entities I want. I would like to fill all the entities by doing an HTTP request to an existing HTTP:PORT that already has my needed information.
I would like to know if it's possible? I'm currently trying with this method that I found online:
private static void sendPOST() throws IOException {
// URL obj = new URL(POST_URL);
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("admin", "admin".toCharArray());
}
});
String url = "http://localhost:8080/api/table-simple-tasks";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// HttpURLConnection con = (HttpURLConnection) URL.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
}
Related
I am trying to create a post request with auth token but I am getting null response. Can you please help me.Can you please let me know what am I missing in the code ?
public static void main(String[] args) {
try {
String url = "https://test.abc.com/";
String token="XXXXXX-abcd-496a-ae73-7659587896";
URL object = new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoInput(true);
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "Bearer " + token);
//Display what the GET request returns
StringBuilder sb = new StringBuilder();
int HttpResult = con.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println(con.getResponseMessage());
} else {
System.out.println(con.getResponseMessage());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
I write this controller and the main idia is that i want to login in another my web application using Post REQUEST. I tested it and the response is 200 OK ! but the controller only redirects me without log me in the another application. Please help.
#Controller
public class BackdoorLoginController {
private final String USER_AGENT = "Mozilla/5.0";
#RequestMapping(value = "/loginTo", method = RequestMethod.GET)
public void redirectWithUsingRedirectPrefix(HttpServletResponse res, HttpServletRequest request)
throws IOException, ServletException {
#SuppressWarnings("restriction")
URL url = new URL(null, "http://www.url.com", new sun.net.www.protocol.https.Handler());
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String urlParameters = "submit=1&email=email#email.com&pass=password";
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("Host", "http://www.url.com");
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
try (DataOutputStream q = new DataOutputStream(con.getOutputStream())) {
q.write(postData);
}
// Send post request
// con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
res.sendRedirect("http://www.url.com");
}
}
I have the following method that works fine, but it throws an exception when the server returns 403 code which results in the method to never return the server response.
public String ping(String lat, String lon)
{
StringBuffer response = null;
try
{
String url = "https://api.mysite.com";
URL urlObj = new URL(url);
HttpsURLConnection con = null;
if (useProxy)
{
con = (HttpsURLConnection) urlObj.openConnection(proxy);
}
else
{
con = (HttpsURLConnection) urlObj.openConnection();
}
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.setRequestProperty("Host", urlObj.getHost());
con.setRequestProperty("Connection", "Keep-Alive");
// con.setRequestProperty("Accept-Encoding", "gzip");
String urlParameters = "{\"lat\":" + lat + ",\"lon\":" + lon + "}";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
// System.out.println("\nSending 'POST' request to URL : " + url);
// System.out.println("Post parameters : " + urlParameters);
// System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
// print result
// System.out.println(response.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
return response.toString();
}
How can I make this return the server response no matter what the server returns and even if the server responds with 403 code (or any other response code)?
You only need to add an if block to make the code more robust like below:
public String ping(String lat, String lon)
{
StringBuffer response = null;
try
{
String url = "https://api.mysite.com";
URL urlObj = new URL(url);
HttpsURLConnection con = null;
if (useProxy)
{
con = (HttpsURLConnection) urlObj.openConnection(proxy);
}
else
{
con = (HttpsURLConnection) urlObj.openConnection();
}
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.setRequestProperty("Host", urlObj.getHost());
con.setRequestProperty("Connection", "Keep-Alive");
// con.setRequestProperty("Accept-Encoding", "gzip");
String urlParameters = "{\"lat\":" + lat + ",\"lon\":" + lon + "}";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
response = readResponse(con.getInputStream());
} else {
response = readResponse(con.getErrorStream());
}
// print result
System.out.println(response.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
return response.toString();
}
private StringBuffer readResponse(InputStream in) {
BufferedReader in = new BufferedReader(new InputStreamReader(in));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
return response;
}
HTH.
I'm currently trying to log in to a php server using HttpURLConnection. I have been successfully able to connect to the server/website as the response code I'm getting back is 200.
getPageContent has a response code of 200 while sendPost has a response code of 0. I am unsure about which getRequestProperty's are necessary and which aren't. I have looked at the elements and response and request headers and form data to get the correct information for the properties I did include however.
I can't really make too much sense of the string coming out of getPageContent as it is quite long but it does seem to be correct. getFormParams could possibly be outputting an incorrect string but information such as the username and password are included so I am unsure.
I'm stuck as to what's wrong or right in my attempt. Am I getting the form parameters correctly? And how do I send the login data correctly?
I call:
String page = getPageContent(URL);
String PostParams = getFormParams( page, "user", "pass" );
sendPost( URL, PostParams );
And the functions are:
private String getPageContent(String url) throws Exception {
URL obj = new URL( url );
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
conn.setRequestProperty("User-Agent", AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = conn.getResponseCode();
MainActivity.globalV.responsecode = responseCode;
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie"));
MainActivity.globalV.getPageContent = responseCode;
return response.toString();
}
public String getFormParams(String html, String username, String password)
throws UnsupportedEncodingException {
Document doc = Jsoup.parse(html);
Elements inputElements = doc.getElementsByTag("input");
List<String> paramList = new ArrayList<String>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
if (key.equals("user_username"))
value = username;
else if (key.equals("user_password"))
value = password;
paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
// build parameters list
StringBuilder result = new StringBuilder();
for (String param : paramList) {
if (result.length() == 0) {
result.append(param);
} else {
result.append("&" + param);
}
}
return result.toString();
}
private void sendPost(String url, String postParams) throws Exception {
URL obj = new URL( url );
HttpURLConnection conn = ( HttpsURLConnection) obj.openConnection();
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "host website");
conn.setRequestProperty("User-Agent", AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", "referer url");
conn.setRequestProperty("Content-Type", "text/html");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
MainActivity.globalV.sendPost = conn.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}
I'm trying to brute force a simple login form I myself created on my website. Initially I used WebScarab's fuzzer plugin, it's pretty fast. Then I want to customize more so I think I can get the brute force done with very simple coding. But to my surprise, my Java code runs so slow: about 2.5 request per second, which is much slower than the plugin of WebScarab... I feel I'm not doing the connection part right maybe..
Any help? Thanks!
public class HTTPURLConnection {
int guessPassword = 0;
public static void main(String[] args) throws Exception {
HTTPURLConnection http = new HTTPURLConnection();
System.out.println("Start!");
//I'm simply guessing password ranging from 0 to 200
for (int i =0; i<200; i++) {
if(http.sendPost())
break;
}
System.out.println("Done!");
}
private boolean sendPost() throws Exception {
String url = "http://mywebsite.com/myfile.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0 etc.");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Accept", "*/*");
con.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
guessPassword ++;
String urlParameters = "name=userName&pwd="+guessPassword;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//if password is not correct, my form should return false
if (response.toString().equals("false"))
return false;
else
return true;
}
}
You could change the input size of the BufferedReader to be bigger....
Try using the same url object instead of re-creating it each time....
Also, you can run this method multiple times at the same time as threads....
class HTTPThread extends Thread {
URL url;
boolean success = false;
String pass;
PrimeThread(Url url,String pass) {
this.url = url;
this.pass = pass;
}
public void run() {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0 etc.");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Connection", "keep-alive");
con.setRequestProperty("Accept", "*/*");
con.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
String urlParameters = "name=userName&pwd="+pass;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//if password is not correct, my form should return false
if (response.toString().equals("false"))
success= false;
else
success= true;
}
}
public String getPassword(){return pass;}
public boolean isSuccess(){return success;}
}