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.
Related
I need to introduce these header elements: Enable MTOM, Force MTOM, WSS-PasswordType: PasswordDigest, WSS TimeToLive: 50 and basic authentication with user and password, and I need to attach a document to this soap request. I have searched for documentation on HttpURLConnection but i couldn't find anything.
My code currently:
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.lang.StringUtils;
public class Send_XML_Post_Request_1 {
public static void main(String[] args) throws MalformedURLException, IOException {
String urlString = "https://ws1.soc.com.br/WSSoc/services/UploadArquivosWs?wsdl";
URL urlForInfWebSvc = new URL(urlString);
URLConnection UrlConnInfWebSvc = urlForInfWebSvc.openConnection();
HttpURLConnection httpUrlConnInfWebSvc = (HttpURLConnection) UrlConnInfWebSvc;
httpUrlConnInfWebSvc.setDoOutput(true);
httpUrlConnInfWebSvc.setDoInput(true);
httpUrlConnInfWebSvc.setAllowUserInteraction(true);
httpUrlConnInfWebSvc.setRequestMethod("POST");
httpUrlConnInfWebSvc.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8");
OutputStreamWriter infWebSvcReqWriter = new OutputStreamWriter(httpUrlConnInfWebSvc.getOutputStream());
String infWebSvcRequestMessage = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://services.soc.age.com/\"> <soapenv:Header/> <soapenv:Body> <ser:uploadArquivo> <arg0> <arquivo></arquivo> <classificacao>FICHA_CLINICA_BRANCO</classificacao> <codigoEmpresa>297819</codigoEmpresa> <codigoFuncionario>3866</codigoFuncionario> <codigoSequencialFicha>133382762</codigoSequencialFicha> <extensaoArquivo>PDF</extensaoArquivo> <identificacaoVo> <chaveAcesso>1e93a60985ff95e</chaveAcesso> <codigoEmpresaPrincipal>62168</codigoEmpresaPrincipal> <codigoResponsavel>17863</codigoResponsavel> <homologacao>false</homologacao> <codigoUsuario>422450</codigoUsuario> </identificacaoVo> <nomeArquivo>TESTE</nomeArquivo> <sobreescreveArquivo>false</sobreescreveArquivo> </arg0> </ser:uploadArquivo> </soapenv:Body> </soapenv:Envelope>";
infWebSvcReqWriter.write(infWebSvcRequestMessage);
infWebSvcReqWriter.flush();
BufferedReader infWebSvcReplyReader = new BufferedReader(new InputStreamReader(httpUrlConnInfWebSvc.getInputStream()));
String line;
String RetornoWS = "";
while ((line = infWebSvcReplyReader.readLine()) != null) {
RetornoWS = RetornoWS.concat(line);
}
infWebSvcReqWriter.close();
infWebSvcReplyReader.close();
httpUrlConnInfWebSvc.disconnect();
String Resposta = StringUtils.substringBetween(RetornoWS,"<return>","</return>");
System.out.println(Resposta);
}
}```
You already set one header property using
httpUrlConnInfWebSvc.setRequestProperty("Content-Type","application/soap+xml; charset=utf-8");
Similar way you can pass
httpUrlConnInfWebSvc.setRequestProperty("Enable MTOM","true");
httpUrlConnInfWebSvc.setRequestProperty("Force MTOM","true");
httpUrlConnInfWebSvc.setRequestProperty("WSS-PasswordType","PasswordDigest");
httpUrlConnInfWebSvc.setRequestProperty("WSS TimeToLive","50");
For a basic authentication header, set authorization
String credentials = "user:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(credentials.getBytes()));
httpUrlConnInfWebSvc.setRequestProperty ("Authorization", basicAuth);
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());
}
}
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 completely new to Java web services. I have written following code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("www.somehost.com/somedata");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed: HTTP error code: " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()
));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My task is to create a web service that returns data in JSON format from "some URL". I want to create a RESTful web service but I do not realize how to modify the code to serve it as a web service. Can anybody explain/show what else I should do?
Here is a Jersey resource example:
#Path("rest/heartbeat")
public class HeartbeatResource {
#GET
#Produces(MediaType.APPLICATION_XML)
public Response heartbeatGet() {
return Response.status(Status.OK).type(MediaType.APPLICATION_XML)
.entity(new Messages("I am alive!")).build();
}
}
Do some research and choose a solid REST framework, if it happens to be Jersey then you can find needed learning documents at: https://jersey.java.net/
I prefer Apace Wink to develop RESTful services.. It gives you capability to tune the API as per you need .
http://wink.apache.org/
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.