Retrieve data with HttpUrlConnection even with bad http codes 403. 404, etc - java

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.

Related

JAVA rest assure get request with auth token

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

Is it possible to fill entities on JHipster from an HTTP?

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

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

Android - Logging in to a php server

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

Categories

Resources