HttpUrlConnection works in Java, 301 in Android - java

I am trying to write an Android app that on startup automatically authenticates the user at a preset webpage I have no control over. I tried it using a POST-Request (following a GET-Request in order to get the cookies needed for authentication) but I ended up receiving a 301 - Moved Permanently Error.
However, the same code worked perfectly in Java.
InputStream inputStream = null;
int length = 100;
try {
URL url = new URL(site);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", host);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
conn.setRequestProperty("Referer", referer);
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Cookie", cookie);
conn.setInstanceFollowRedirects(false);
conn.setDoInput(true);
conn.setDoOutput(true);
//setting parameters needed for login
List<AbstractMap.SimpleEntry> params = new ArrayList<>();
params.add(new AbstractMap.SimpleEntry("type", type));
params.add(new AbstractMap.SimpleEntry("console", console));
params.add(new AbstractMap.SimpleEntry("login[password]", password));
params.add(new AbstractMap.SimpleEntry("login[mail]", username));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
//write converted parameters
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
int response = conn.getResponseCode();
Log.d(TAG, "The response is: " + response + "\n" + conn.getResponseMessage());
inputStream = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = convertInputStreamToString(inputStream, length);
Log.d(TAG, "Content of Webpage: " + contentAsString);
} finally {
if (inputStream != null) {
inputStream.close();
}
}

Related

Sending 'DELETE' request to URL Response Code : 403 in java

I want to delete the API from url : "http://dublr024vm.devlab.ibm.com:60633/B2BiAPIs/svc/cadigitalcertificates/_id:tibco_ssl" , I am getting java.io.IOException: Server returned HTTP response code: 403 for URL. I have passed the correct authentication details too.
Below is the part of my code:
public static void call_me() throws Exception {
InputStream is = null;
String url = "http://dublr024vm.devlab.ibm.com:60633/B2BiAPIs/svc/cadigitalcertificates/_id:tibco_ssl";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");
con.setDoOutput(true);
System.setProperty("http.agent", "Chrome");
// optional default is DELETE
con.setRequestMethod("DELETE");
//add request header
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
byte[] message = "admin:password".getBytes("UTF-8");
String encoding = DatatypeConverter.printBase64Binary(message);
con.setRequestProperty("Authorization", "Basic "+new String(encoding));
con.connect();
is = obj.openConnection().getInputStream();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'DELETE' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line, responseText = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
responseText += line;
}
br.close();
con.disconnect();
}

Request Transaction-List from Paypal

I try to request a transaction list from paypal but I allways get HTTP-Code 400
public void getTransactionList(String accessToken)
{
try
{
URL url = new URL(
"https://api.sandbox.paypal.com/v1/reporting/transactions"
+ "?start_date=2018-01-01T00:00:00Z&end_date=2018-04-01T00:00:00Z"
+ "&fields=all&page_size=100&page=1");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept-Language", "en_US");
conn.setUseCaches(false);
conn.setDoOutput(true);
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
reader.close();
}
catch (Throwable e)
{
e.printStackTrace();
//throw new ActionException(e);
}
}
The Exception is
java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.sandbox.paypal.com/v1/reporting/transactions?start_date=2018-01-01T00:00:00-000&end_date=2018-04-02T00:00:00-000&fields=all&page_size=100&page=1
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
at de.crefo.workflow.paypal.http.HttpRestClient.getTransactionList(HttpRestClient.java:42)
at de.crefo.workflow.paypal.http.HttpRestClient.main(HttpRestClient.java:112)
The Access-Token request, I do in a similar way, is working perfectly fine and gives me a valid token.
What am I doing wrong?
EDIT. Changed dateformat in URL, see comments.

How get response status

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

httpurlConnection with httpParams in java

I'm trying to post a file from local to another platform over a switch. When i do it with DefaultHttpClient there is no problem.
HttpParams params = new BasicHttpParams();
params.setParameter(ConnRoutePNames.LOCAL_ADDRESS, InetAddress.getByName(interfaceIp));
DefaultHttpClient httpClientPost = new DefaultHttpClient(params);
But i have to do it with HttpURLConnection. Is there a way to do this?
for example:
httpConn = (HttpURLConnection) url.openConnection(myHttpParams);
here is my HttpUrlConn codes
url = new URL(baseUrl+"/html/uploadimage.cgi");
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" +"----WebKitFormBoundary"+boundary);
httpConn.setRequestProperty("Host", "192.168.1.1");
httpConn.setRequestProperty("Connection", "keep-alive");
httpConn.setRequestProperty("Content-Length", "16551361");
httpConn.setRequestProperty("Cache-Control", "max-age=0");
httpConn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpConn.setRequestProperty("Origin", "http://192.168.1.1");
httpConn.setRequestProperty("Upgrade-Insecure-Requests", "1");
httpConn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36");
httpConn.setRequestProperty("Referer", baseUrl + "/html/advance.html");
httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
httpConn.setRequestProperty("Accept-Language", "tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4");
String cookie = "Username="+ username +"; " +
"Password="+ cyreptedPassword +"; Language=tk; " +
"username="+ username +"; " +
"SessionID_R3="+ sessionID +"; activeMenuID=maintain_settings; activeSubmenuID=device_mngt";
httpConn.setRequestProperty("Cookie", cookie);
httpConn.setAllowUserInteraction(true);
httpConn.setConnectTimeout(9999*9999999);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
thanks for all.
HttpUrlConnection does not use http params, but it uses proxy.
here is some information about httpUrlConnection example.

how to work with jsoup in case of Soap request/response?

I am trying to scrape this link but failing to do so as it takes a soap request and return results as HTML via soap response.
Here's my Code that is not working properly.
Connection.Response response = Jsoup.connect("http://www.itatonline.in:8080/itat/jsp/runBirt2.jsp?subAction=showReoprt&__report=CaseDetails1_DELHI.rptdesign&searchWhat=searchByAssName&Serial%20No=&Appeal%20No=&Assessee%20Name=&AssType=DontKnow&appealDate=&Bench=AGR").method(Method.GET).timeout(30000).execute();
String url = "http://www.itatonline.in:8080/itat/jsp/runBirt2.jsp?subAction=showReoprt&__report=CaseDetails1_DELHI.rptdesign&searchWhat=searchByAssName&Serial%20No=&Appeal%20No=&Assessee%20Name=k&AssType=DontKnow&appealDate=&Bench=AGR&__sessionId=20151210_231624_579";
String rawData = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/>"
+ "<soap:Body><GetUpdatedObjects xmlns=\"http://schemas.eclipse.org/birt\">"
+ "<Operation><Target><Id>Document</Id><Type>Document</Type></Target><Operator>GetPage</Operator><Oprand><Name>Appeal No</Name><Value></Value></Oprand><Oprand><Name>__isdisplay__AppealNo</Name><Value></Value></Oprand><Oprand><Name>Serial No</Name><Value></Value></Oprand><Oprand><Name>__isdisplay__Serial No</Name><Value></Value></Oprand><Oprand><Name>Assessee Name</Name><Value>k</Value></Oprand><Oprand><Name>__isdisplay__Assessee Name</Name><Value>k</Value></Oprand><Oprand><Name>searchWhat</Name><Value>searchByAssName</Value></Oprand><Oprand><Name>__isdisplay__searchWhat</Name><Value>searchByAssName</Value></Oprand><Oprand><Name>AssType</Name><Value>DontKnow</Value></Oprand><Oprand><Name>__isdisplay__AssType</Name><Value>DontKnow</Value></Oprand><Oprand><Name>appealDate</Name><Value></Value></Oprand><Oprand><Name>__isdisplay__appealDate</Name><Value></Value></Oprand><Oprand><Name>Bench</Name><Value>AGR</Value></Oprand><Oprand><Name>__isdisplay__Bench</Name><Value>AGR</Value></Oprand><Oprand><Name>__page</Name><Value>1</Value></Oprand><Oprand><Name>__svg</Name><Value>true</Value></Oprand><Oprand><Name>__page</Name><Value>1</Value></Oprand><Oprand><Name>__taskid</Name><Value>2015-11-9-23-16-22-34</Value></Oprand></Operation></GetUpdatedObjects></soap:Body></soap:Envelope>";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
con.setRequestProperty("Cookie", response.cookies().toString().replaceAll("[{}]", ""));
con.setRequestProperty("Host", "www.itatonline.in:8080");
con.setRequestProperty("Referer", "http://www.itatonline.in:8080/itat/jsp/runBirt2.jsp?subAction=showReoprt&__report=CaseDetails1_DELHI.rptdesign&searchWhat=searchByAssName&Serial%20No=&Appeal%20No=&Assessee%20Name=k&AssType=DontKnow&appealDate=&Bench=AGR");
con.setRequestProperty("SOAPAction", "");
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; rv:42.0) Gecko/20100101 Firefox/42.0");
con.setRequestProperty("X-Prototype-Version", "1.4.0");
con.setRequestProperty("X-Requested-With", "XMLHttpRequest");
con.setRequestProperty("request-type", "SOAP");
// Send post request
con.setDoOutput(true);
OutputStreamWriter w = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
w.write(rawData);
w.close();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer resp = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
resp.append(inputLine);
}
in.close();
System.out.println(resp);
`

Categories

Resources