How get response status - java

All good day!
Example code:
try {
URL object = new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.setRequestProperty("Accept", "application/json; charset=utf-8");
con.setRequestMethod("POST");
OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(json);
wr.flush();
InputStream inputStream = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line=reader.readLine()) != null) {
response += "\n" + line;
}
How to get the status of a response?
Please, help!

con.getResponseCode();` // get status

Related

Login to another application after post request Spring JAVA

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");
}
}

While making post call i am getting below exception

Error description:
java.lang.NoSuchMethodError: org.apache.http.HttpHost.getAddress()Ljava/net/InetAddress;
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:102)
Could anyone help me here....what i am missing ???
use below sample code :
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=& num=12345";
// 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());
}
}

Jersey post method request sending with payload

URL url = new URL("http://nvmbd1bkb150v03.rjil.ril.com/system/ws/v11/gh/search/?portalId=400100000001003&usertype=customer&$format=json");
String payload="portalId=400100000001003&Q1-1-1000000931=1000000919&usertype=customer&%24format=json";
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("session_id", session_id);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
//writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
//br.close();
//connection.disconnect();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
out.println(jsonString.toString());
This is all my code. I want to read that web service but it is giving me error. Please help.

How to Decode a xml Sent over Url in java

I am firing an online xml in java to the method below:
public String WriteToServer(String xml) {
StringBuilder answer = new StringBuilder();
try {
String myurl="example.com";
URL url = new URL(myurl);
URLConnection conn = url.openConnection(Proxy.NO_PROXY);
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(xml);
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
writer.close();
reader.close();
} catch (Exception e) {
System.out.println(e);
}
return answer.toString();
}
My Problem is that the server receives an encoded xml so it can not understand and returns a 500 response to the client. How can I decode a xml to a plain text that the server can read?
Try below code just before creating OutputStreamWriter instance
String myurl="example.com";
URL url = new URL(myurl);
URLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Language", "en-US");
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);

Brute Force with Java HTTP URL Connection

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;}
}

Categories

Resources