Https connection Android with Http authentication - java

I want to make a HTTPS connection with a webservice in Android Studio but it doesn't work with the code that I have written. I get a FileNotFound Exception.
My URL is working in the browser.
And response code is 400.
This is my code:
protected Void doInBackground(String... params) {
String https_url = "HERE MY HTTPS URL";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String userPassword = "USERNAME" + ":" + "PASSWORD";
String encoding = new String(Base64.encode(userPassword.getBytes(), Base64.DEFAULT));
con.setRequestProperty("Authorization", "Basic " + encoding);
con.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
con.setRequestProperty("Accept","*/*");
//dumpl all cert info
print_https_cert(con);
//dump all the content
print_content(con);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Someone who can help me out?

Related

Java HTTP Request for PHP

So i am trying to send some variables to my localhost which runs a php file which should output the variable.
URL url = null;
try {
String charset = "UTF-8";
String MontagMittagVorspeise = "value1";
String query = String.format("param1=%s", URLEncoder.encode(MontagMittagVorspeise, charset));
url = new URL("127.0.0.1/Haunsbot/Hauns.php");
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
And this is my PHP:
<?php
if(isset($_GET["MontagMittagVorspeise"]))
{echo "Vehicle :".$_GET["MontagMittagVorspeise"];}
?>
And IntelliJ gives me the following error: java.net.MalformedURLException: no protocol: 127.0.0.1/Haunsbot/Hauns.php
Can someone help me?:)

Coverting java request to c#

I am trying to convert this request written java to c#(Xamarin android) , java one seems to be working , but c# one is failing with bad request(400) .
Could you please point out if i am translating rightly ?
Java code
String url = "https://someUrl";
try {
URL url1 = new URL(url);
URLConnection uc = url1.openConnection();
String basicAuth = Base64.encodeToString((APIKEY).getBytes("UTF-8"), Base64.NO_WRAP);
uc.setRequestProperty("Authorization", basicAuth);
InputStream in = uc.getInputStream();
// Log.e(TAG, "response: " + response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
C# code
String url = "https://someUrl";
// Add custom implementation here as needed.
var uri = new Uri(url);
var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes (API_KEY), Base64FormattingOptions.None);
try
{
using(var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", authHeaderValue);
var response = await client.GetAsync(uri);
}
}
catch (Exception e)
{
Log.Debug ("TokenSending", "failed to send token" + e);
}

How to get cookies from HTTP response performed via Endpoint method?

I am trying to create an endpoint method, which is supposed to log me in to a different system and return the authorization cookie's value for further use in my application. Even though my method successfully logs me to the system (I checked the response data), i cannot retrieve the cookie from header files of the response. This is the bean's method called from endpoint method.
public String login (String password, String name) {
String urlParameters = "destination=" + MAILBOX_URL_SUFFIX + "&credential_0=" + name +
"&credential_1=" + password + "&login=Prihl%E1si%BB+sa";
URL url = null;
// ***************** login ***********************
try {
URI uri = new URI("https", "is.stuba.sk", "/system/login.pl", null);
url = uri.toURL();
} catch (Exception e) {
e.printStackTrace();
}
HttpURLConnection con = null;
try {
con =(HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
appendRequestHeader(con);
//Send post request
con.setDoOutput(true);
DataOutputStream wr = null;
try {
wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
con.connect();
con.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
String cookie = "default";
String headerName=null;
for (int i=1; (headerName = con.getHeaderFieldKey(i))!=null; i++) {
cookie.concat(con.getHeaderField(i));
}
return cookie;
}
EDIT: the method returns "default" all the time, none Set-Cookie, nor the other cookies
Before, when i was not running the method from server-side the code started with
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
... and instead of using con.headerField i used this, to successfully get my cookie.
return manager.getCookieStore().getCookies().get(0).getValue();
However CookieManager is blacklisted for Google Cloud Endpoints and i cannot retrieve the cookie any other way :(
Any suggestions? Thank you!

Using Java (HttpURLConnection) to authenticate to Restheart (for Mongodb)

I am using restheart to provide a restful interface to mongodb. The interface is set up and running and provides the correct answer if a GET request is sent through Chrome. However if I use the following java code using a HttpURLConnection I get a 201 response with no content.
try {
videos = new URL("http://www.example.com:8080/myflix/videos");
} catch (Exception et) {
System.out.println("Videos URL is broken");
return null;
}
HttpURLConnection hc = null;
try {
hc = (HttpURLConnection) videos.openConnection();
String login="admin:admin";
final byte[] authBytes = login.getBytes(StandardCharsets.UTF_8);
final String encoded = Base64.getEncoder().encodeToString(authBytes);
hc.addRequestProperty("Authorization", "Basic "+encoded);
hc.setDoInput(true);
hc.setDoOutput(true);
hc.setUseCaches(false);
hc.setRequestMethod("GET");
hc.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
hc.setRequestProperty("Content-Type", "application/json");
hc.setRequestProperty("Accept", "application/json,text/html,application/hal+json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*");
} catch (Exception et) {
System.out.println("Can't prepare http URL con");
return (null);
}
BufferedReader br = null;
try {
OutputStreamWriter writer = new OutputStreamWriter(
hc.getOutputStream());
} catch (Exception et) {
System.out.println("Can't get reader to videos stream");
}
String inputLine;
String sJSON = null;
try {
int rc = hc.getResponseCode();
What is the correct way to authenticate using Java to the resthert interface? (Details on the restheart authentication is here Restheart authentication
I made few changes (look for inline comments starting with <==) and it works:
The way you generate the authentication request header is correct. When I run your code I actually got 415 Unsupported Media Type, that went away commenting out hc.setDoOutput(true). A GET is a input operation, in fact you were also trying to get an OutStream from the connection: you need to get an InputStream actually.
URL url;
try {
url = new URL("http://127.0.0.1:8080/test/huge");
} catch (Exception et) {
System.out.println("Videos URL is broken");
Assert.fail(et.getMessage());
return;
}
HttpURLConnection hc = null;
try {
hc = (HttpURLConnection) url.openConnection();
String login = "admin:admin";
final byte[] authBytes = login.getBytes(StandardCharsets.UTF_8);
final String encoded = Base64.getEncoder().encodeToString(authBytes);
hc.addRequestProperty("Authorization", "Basic " + encoded);
System.out.println("Authorization: " + hc.getRequestProperty("Authorization"));
hc.setDoInput(true);
//hc.setDoOutput(true); <== removed, otherwise 415 unsupported media type
hc.setUseCaches(false);
hc.setRequestMethod("GET");
hc.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
hc.setRequestProperty("Accept", "application/json,text/html,application/hal+json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*");
} catch (Exception et) {
System.out.println("Can't prepare http URL con");
}
System.out.println(hc.toString());
BufferedReader br = null;
try {
InputStreamReader reader = new InputStreamReader(hc.getInputStream()); // <== the request is a GET, data is in input
} catch (Exception et) {
System.out.println("Can't get reader to videos stream");
}
int rc = hc.getResponseCode();
System.out.println("response code: " + rc);
System.out.println("response message: " + hc.getResponseMessage());
Assert.assertEquals(200, rc);

Load certificate previosly imported manually [ANDROID] [HTTPS]

I added a self signed-certificate (https) manually in Settings-> Security-> Trusted certificates.
And if i try to access to my server using google chrome runs OK (previosly accept message). But in my Android application, using HttpsURLConnection class,crashes.
This is my code:
try {
URL obj = new URL(url);
HttpsURLConnection conn;
conn = (HttpsURLConnection) obj.openConnection();
conn.setConnectTimeout(timeOut);
conn.setRequestMethod("GET");
StatusCode = conn.getResponseCode();
Log.i(TAG_GET, "Status Code: " + StatusCode);
InputStream body = null;
try {
body = conn.getInputStream();
} catch (Exception e) {
e.printStackTrace();
body = conn.getErrorStream();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I think that I need load certificates installed on my device, but how can I do?
Thanks

Categories

Resources