I'm trying to make a request with java on this OData2 API => https://scihub.copernicus.eu/dhus/odata/v1/ for a project. But I can't without authentication. I have personal logs, as a user I don't have any problems. When I tried with java it gave an error 401.
I try this:
String auth = user + ":" + password;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
String basicAuth = "Basic " + new String(new Base64().encode(auth.getBytes()));
connection.setRequestProperty("Authorization", basicAuth);
connection.connect();
int responseCode = connection.getResponseCode();
System.out.println(responseCode);
System.out.println(url.toString());
But it doesn't works. When i print the responseCode i have a 400 error and i try also another code it was a 401 error.
With PostMan i only need the BasicAuth to have an access and it works.
And i'm using Olingo2.
I'm new on java web and i don't have any idea.
In the first step i only want to have the authentication.
And then doing queries.
Thank you!
For the 401 case there is something wrong with the authorization,otherwise the general approach is right.
For the 400 case, browsers and tools like postman will automatically send additional headers, which the code will be missing. I reused the about code and passed an additional header Accept : application/xml and was able to retrieve the response. Below is the working code. Cheers!
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Test1 {
public static void main(String[] args) throws IOException {
String user = "ENTER YOUR USERNAME";
String password = "ENTER YOUR PASSWORD";
String auth = user + ":" + password;
URL url = new URL("https://scihub.copernicus.eu/dhus/odata/v1/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
String basicAuth = "Basic " + Base64.getEncoder().encodeToString((auth).getBytes(StandardCharsets.UTF_8)); // Java
connection.setRequestProperty("Authorization", basicAuth);
connection.connect();
System.out.println(connection.getResponseCode());
System.out.println(connection.getContent());
}
}
Related
I'm using client credential secret to run API on Microsoft Endpoint (Intune).
Example used from link.
Getting access token. (Working)
Get android Managed App Protections. (Working using GET HTTP Method)
Patch Request. (Not Working)
The examples do not mention any PATCH or POST request, hence need some help for it.
I tried the below code snippet but it fails.
private void setAndroidModels(final String accessToken, final String policyId, final String modelList)
throws IOException {
URL url = new URL(
"https://graph.microsoft.com/beta/deviceAppManagement/androidManagedAppProtections/" + policyId);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PATCH");
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = modelList.getBytes();
os.write(input, 0, input.length);
}
int httpResponseCode = conn.getResponseCode();
System.out.println("POST Response Code : " + httpResponseCode);
System.out.println("POST Response Message : " + conn.getResponseMessage());
}
Result : Exception in thread "main" java.net.ProtocolException: Invalid HTTP method: PATCH
Also tried
private void setAndroidModels(final String accessToken, final String policyId, final String modelList)
throws IOException {
URL url = new URL(
"https://graph.microsoft.com/beta/deviceAppManagement/androidManagedAppProtections/" + policyId);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("X-HTTP-Method-Override", "PATCH");
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Bearer " + accessToken);
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = modelList.getBytes();
os.write(input, 0, input.length);
}
int httpResponseCode = conn.getResponseCode();
System.out.println("POST Response Code : " + httpResponseCode);
System.out.println("POST Response Message : " + conn.getResponseMessage());
}
Result :
POST Response Code : 400
POST Response Message: Bad Request
How can I get the client credential secret logic working for POST and PATCH HTTP Methods?
We can directly call patch request in MS Graph.
When creating PATCH requests to the API, you need to create a new
PATCH object that contains only the information you want to update.
This should be distinct from any objects you receive from the service
from a GET or a POST.
Please refer Document for more details.
For example, Patch rquest to user
User realMe = graphClient.me().buildRequest().get();
User patchMe = new User();
patchMe.givenName = "Beth";
realMe = graphClient
.users(realMe.userPrincipalName)
.buildRequest()
.patch(patchMe);
I want to call GET and POST API in java without using any framework. I need to use basic authentication. Can anybody help me with some tutorial link. In google I found code only in spring framework, But I am not using Spring. I am looking for code to call API with basic authentication.
I have to add new url with authentication in the below code. What modification is required if API is secured with basic auth and it is POST method. I am new to java so not much aware.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
public class NetClientGet {
public static void main(String[] args) {
try
{
System.out.println("Inside the main function");
URL weburl=new URL("http://dummy.restapiexample.com/api/v1/employees");
HttpURLConnection conn = (HttpURLConnection) weburl.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
System.out.println("Output is: "+conn.getResponseCode());
System.out.println("Output is: ");
System.setProperty("http.proxyHost", null);
//conn.setConnectTimeout(60000);
if(conn.getResponseCode()!=200)
{
System.out.println(conn.getResponseCode());
throw new RuntimeException("Failed : HTTP Error Code: "+conn.getResponseCode());
}
System.out.println("After the 2 call ");
InputStreamReader in=new InputStreamReader(conn.getInputStream());
BufferedReader br =new BufferedReader(in);
String output;
while((output=br.readLine())!=null)
{
System.out.println(output);
}
conn.disconnect();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Basic Authentication
See the RFC #2617 section 2: Basic Authentication Scheme
Add Authentication header into the request. Here's an example:
String username = "john";
String password = "pass";
// ...
URL weburl=new URL("http://dummy.restapiexample.com/api/v1/employees");
HttpURLConnection conn = (HttpURLConnection) weburl.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
// snippet begins
conn.setRequestProperty("Authorization",
"Basic " + Base64.getEncoder().encodeToString(
(username + ":" + password).getBytes()
)
);
// snippet ends
System.out.println("Output is: "+conn.getResponseCode());
POST Method
See this answer for more information about using POST method with HttpURLConnection.
I'm trying to establish a Connection via HTTPS. I also set the "Authorization" property in the Request Header to Basic and provide an encoded auth string accordingly.
I checked with the Firefox Plugin HttpRequester and everythign works fine, which means I entered the url, choose "GET" as request method, add the Authorization to the header and after pressing submit I get back some xml which only a properly authorized user should get.
Unfortunately I can neither provide you with the actual auth info nor the real url in the SSCCE. However, I can tell you, that the Auth seems to work, since I get a 200 response. I also changed the Auth to a wrong value and get a "401 Authorization Required" response then.
It actually seems like the "?myparam=xyz" is somehow cut off, because when I remove this parameter from the url and test with Firefox HttpRequester again I get the same response as in Java.
Unfortunately I have no access to "theirdomain.com", so I don't know what's happending on the server side. But since it works with the Firefox HttpRequester, it should also work with Java.
What could be the reason? Thanks for your help!
EDIT:
I changed the url to "https://www.google.com/search?q=foo" and commented this line:
//con.setRequestProperty("Authorization", auth);
I can see from the returned string, that google received the "foo". So apparently the combination of Authorization and get parameter seems to be the problem, since both separately work fine.
SSCCE:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpRequest
{
/**
* #param args
*/
public static void main(final String[] args)
{
System.out.println("start request");
final String urlString = "https://theirdomain.com/foo/bar/bob?myparam=xyz";
final String auth = "Basic XyzxYzxYZxYzxyzXYzxY==";
HttpsURLConnection con;
try
{
final URL url = new URL(urlString);
con = (HttpsURLConnection) url.openConnection();
con.setRequestProperty("Authorization", auth);
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
con.setRequestMethod("GET");
// con.setDoOutput(true);
con.connect();
final int responseCode = con.getResponseCode();
if (responseCode != 200)
System.out.println("Server responded with code " + responseCode + " " + con.getResponseMessage());
else
{
System.out.println("Starting to read...");
final InputStream inStream = con.getInputStream();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while (inStream != null && (c = inStream.read()) != -1)
{
baos.write(c);
}
System.out.println(new String(baos.toByteArray()));
}
}
catch (final IOException e)
{
System.out.println("could not open an HTTP connection to url: " + urlString);
e.printStackTrace();
}
finally
{
System.out.println("end request");
}
}
}
Have you tried adding
con.setRequestProperty("myparam", "xyz"); to your code?
I am trying to Connect to url using URLConnection, in java with username and password.
This is the following code I am using:
package com.nivi.org.client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.sun.jersey.core.util.Base64;
public class GetURLContent {
public static void main(String[] args) {
URL url;
try {
url = new URL("http://sampleurl.co.uk");
URLConnection conn = url.openConnection();
String username = "username";
String password = "password";
String Token = "zzzzzzzzzzzzzzzzzzzzz";
System.setProperty("http.proxyHost", "proxyhostname");
System.setProperty("http.proxyPort", "8080");
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestProperty ("Token", Token);
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
System.out.println("br............."+br.toString());
br.close();
System.out.println("Done");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
=======================================
I am getting the following error
java.io.IOException: Server returned HTTP response code: 403 for URL:
http://sampleurl.co.uk
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
at com.nivi.org.client.GetURLContent.main(GetURLContent.java:63)
=======================================
First of all my question is
Are these following lines in the code are correct?
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestProperty ("Token", Token);
Are these following lines in the code are correct?
It depends on how the actual website you are accessing implements its user authentication.
What you appear to be doing is a combination of HTTP Basic Authentication (i.e. the Authorization header), and something involving a non-standard header called Token. This may be sufficient, if the website supports Basic Authentication.
You should probably read the website's programmer documentation of how their web APIs work. If there isn't any such documentation available to you, use your browsers web development tools to identify the mechanism that the site is using when you log in via a web browser ... and attempt to get your client to behave the same way.
One thing to note is that sending a Basic authorization response in an HTTP request is insecure. Use an HTTPS request if that is an option.
I'm using Java to access a HTTPS site which returns the display in an XML format. I pass the login credentials in the URL itself. Here is the code snippet:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
requestURL = "https://Administrator:Password#localhost:8443/abcd";
try {
InputStream is = null;
URL url = new URL(requestURL);
InputStream xmlInputStream =new URL(requestURL).openConnection().getInputStream();
byte[] testByteArr = new byte[xmlInputStream.available()];
xmlInputStream.read(testByteArr);
System.out.println(new String(testByteArr));
Document doc = db.parse(xmlInputStream);
System.out.println("DOC="+doc);
} catch (MalformedURLException e) {
}
I'm creating a trust manager in the program which does not validate signed/unsigned certificates. But, on running the above program, I get the error
Server returned HTTP response code: 401 for URL: https://Administrator:Password#localhost:8443/abcd
I can use the same url on my browser and it displays the xml correctly. Kindly let me know how to make this work within the Java program.
401 means "Unauthorized", so there must be something with your credentials.
I think that java URL does not support the syntax you are showing. You could use an Authenticator instead.
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(login, password.toCharArray());
}
});
and then simply invoking the regular url, without the credentials.
The other option is to provide the credentials in a Header:
String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);
PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.
Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package
import sun.misc.BASE64Encoder;
import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;
and then,
String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );
public String getAuthantication(String username, String password) {
String auth = new String(Base64.encode(username + ":" + password));
return auth;
}