I'm working on a client that consumes a rest API with header Authorization. I'm getting a hard time getting to work adding http header authorization. I'm using the code below:
package com.javap;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Properties;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
sslUtil.turnOffSslChecking();
Properties prop = new Properties();
//InputStream input = null;
InputStream input = Main.class.getResourceAsStream("./application.properties");
prop.load(input);
String address = prop.getProperty("address");
String token = prop.getProperty("token");
URL url = new URL(address + customerId);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Bearer " + token);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.addRequestProperty("User-Agent", "Mozilla/4.0");
conn.setRequestProperty("Content-Type", "text/plain");
conn.setRequestProperty("charset", "UTF-8");
conn.connect();
if (conn.getResponseCode() != 200) {
hasSQ = "false";
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}else {
Scanner sc = new Scanner(url.openStream());
while(sc.hasNext()){
inline += sc.nextLine();
}
sc.close();
conn.disconnect();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
}
I get an error of 401. But using Postman, everything works fine, son it's defiintely not about the token. Any ideas on how this could be resolved?
Thanks in advance
Solved it! Apparently the connection was a success but I'm reconnecting to the webservice again via url.openStream() without the attached header authorization. That's why. My bad :-p
Thanks.
Related
I'd like to get a bearer token with Java. My API reference says to do a GET with curl:
curl -G "https://api.company.com/api/auth" --data-urlencode "username=<username>" --
data-urlencode "secret=<secret>"
Then, extract the “Value” property or the bearer token from the returned JSON object.
What is the equivalent way to do this with java 8?
Please use something like this:
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class Main {
public static void main(String[] args) {
URL url;
try {
url = new URL("https://api.company.com/api/auth?username=<username>&secret=<secret>");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
System.out.println("Response status: " + status);
System.out.println(content.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Or
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String params = "username=<username>&secret=<secret>";
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("https://api.company.com/api/auth?" + params);
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(response.getStatusLine().getStatusCode());
try {
System.out.println(response.getEntity().getContent());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm using JSON and want to send post request to server via username, password in body and x-auth-app-id, x-auth-app-hash in header..
I have test on Postmen and it return 200 (status ok), But when I build my sources it happen error.
This is my class header:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
public class HttpRequestUtil {
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
InputStream inputStream=null;
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestProperty("x-auth-app-id", "6166611659356156223");
httpUrlConn.setRequestProperty("x-auth-app-hash", "a44f4ea21475fa6761392ba4bc659990bee771c413b2c207490a79f9ec78c2a61234");
httpUrlConn.setRequestProperty("Content-Type", "application/json");
httpUrlConn.setRequestMethod(requestMethod);
if ("POST".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
}
catch (ConnectException ce) {
ce.printStackTrace();
System.out.println("Our server connection timed out");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("https request error:{}");
}
finally {
try {
if(inputStream!=null) {
inputStream.close();
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonObject;
}
}
And class Body:
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class CallCenterController {
public static void main(String[] args) throws JSONException {
String sipUser = "vchi_dd";
String sipPassword = "m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa";
Map<String, Object> sipAccount = new HashMap<String, Object>();
sipAccount.put("sipUser", sipUser);
sipAccount.put("sipPassword", sipPassword);
sipAccount = postData(sipUser, sipPassword);
System.out.println("result: " + sipAccount);
};
public static JSONObject postData(String sipUser, String sipPassword) {
String url="https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser="+sipUser+"&sipPassword="+sipPassword;
return HttpRequestUtil.httpRequest(url, "POST", "");
}
}
When I build it happen an exception following as:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser=vchi_dd&sipPassword=m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa
https request error:{}
result: null
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.mypackage.HttpRequestUtil.httpRequest(HttpRequestUtil.java:63)
at com.mypackage.CallCenterController.postData(CallCenterController.java:45)
at com.mypackage.CallCenterController.main(CallCenterController.java:34)
How to send correct data to my url and fix the problem?
I would use Java HTTP Client API if your java version is high enough.
Here's a link to it https://www.baeldung.com/java-9-http-client
I have used it and it feels more maintainable and clear.
Also, it seems that you're sending the request with empty body even though you say in your question that you are sending username and password in body.
And why are you adding username and password to a map if you are not using the map?
sipAccount.put("sipUser", sipUser);
sipAccount.put("sipPassword", sipPassword);
I want to match issues in JIRA with other datasource.
I can use curl:
curl -u myname:mypassword
https://jira.myorganization.com/rest/api/latest/issue/TR-1234
This will return info about the issue, for exampel TR-1234, that I want to check some data for.
In java I want to do the same thing but I get javax.net.ssl.SSLHandShakeException
The program I try to run:
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
URL url = null;
try {
url = new URL("https://jira.myorganization.com/rest/api/latest/issue/TR-1234");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String userpass = "myusername:mypassword";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
System.out.println("Resp="+ con.getResponseCode()+" "+con.getResponseMessage());
String contentType = con.getHeaderField("Content-Type");
BufferedReader br = new BufferedReader(new InputStreamReader(
(con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can I somehow pass userid and password to the URL. The application is a tool and it would be ok to let the user input his name and password.
It took me a long time to get the proxy for my Java connection working at my office. Now I got it working, but it's VERY slow.
I use the following code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
public class Test {
public static void main(String[] args) {
long millis = System.currentTimeMillis();
URL url;
InputStream is = null;
BufferedReader br;
String line;
try {
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("xxxx",
"xxxx".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
url = new URL("http://stackoverflow.com/");
URLConnection conn = url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("xxx", xxx)));
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (is != null) is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
System.out.println("Duration: "+(System.currentTimeMillis()-millis));
}
}
When I run this, the output is the following:
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
Duration: 222856
As you can see, the proxy is working. I do get the webpage just fine. But it's waiting very long before showing the webpage contents (more than 222 seconds :O). I have no clue what could possibly be the problem here.
Just some information about the environment: I'm working on my office VDI. Google Chrome and IE have internet connection, but other programs don't. By a lot of googling I found the correct proxy settings.
I am trying to hit a url through URL Connection in servlet. The response of the request (which is a pdf) needs to be displayed on the browser as pdf. Here I do not have any temporary pdf file kept on the server which means i want my code to generate the url response as a pdf on the fly. Currently my webservice returns pdf if I hit the webservice url(REST) directly in the browser.
Here is my code
I am getting a blank output
code:
package com.mm;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class testServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\""+ "dummy" + "\"");
byte[] pdfData = servicecall().getBytes("UTF-8");
System.out.println(pdfData.length);
response.setContentLength(pdfData.length);
OutputStream output = response.getOutputStream();
output.write(pdfData);
output.flush();
output.close();
}
public String servicecall()
{
String output = "";
BufferedReader reader = null;
StringBuilder stringBuilder;
try
{
URL url = new URL("http://hardik/Wecs/External/private/document.aspx?prd=1042737~~PDF~~MTR~~IPDS~~EN~~2014-01-10%2014:00:41~~SOLEST%20120~~");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/pdf");
conn.connect();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
reader = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
output = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println( output);
return output;
}
}
I get a blank pdf output