Send Https request through Java but getting unauthorized error-401 - java

I am sending Https request with username and password through 2 ways but in both the cases I am getting Error 401- Unauthorized error
direct connection through URLConnection
try {
URL url = new URL("https://xxx.xxxxx.com/v1/limit/5");
URLConnection urlConnection = url.openConnection();
HttpsURLConnection connection = null;
if(urlConnection instanceof HttpsURLConnection) {
String authStr = "username"+":"+"password";
byte[] bytesEncoded = Base64.encodeBase64(authStr.getBytes());
String authEncoded = new String(bytesEncoded);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Basic "+authEncoded);
} else {
System.out.println("Please enter an HTTPs URL.");
return;
}
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String urlString = "";
String current;
while((current = in.readLine()) != null) {
urlString += current;
}
System.out.println(urlString);
} catch(IOException e) {
e.printStackTrace();
}
Connection through Jersey Client but in the same way I am getting 401-unauth error

Related

Why does my httpurlconnection throw a 500 error?

I'm trying to get my game server to link up with my Xenforo forums but it pulls a 500 error when trying to connect.
Its definitely reading the databases as i can type an incorrect username when logging in and it will tell me to register. But if i use a username that exists it throws the error.
This is the error in my Central server console :
java.io.IOException: Server returned HTTP response code: 500 for URL: http://localhost//extra/xenforo/index.php
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1900)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1498)
at io.ruin.api.utils.PostWorker.post(PostWorker.java:65)
at io.ruin.api.utils.PostWorker.postArray(PostWorker.java:82)
at io.ruin.api.utils.XenPost.post(XenPost.java:14)
at io.ruin.central.model.world.WorldLogin.lambda$new$0(WorldLogin.java:33)
at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1626)
at java.util.concurrent.CompletableFuture$AsyncRun.exec(CompletableFuture.java:1618)
at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
I've tried messing with the post string but can't get it to connect keeps catching IOException E
public class PostWorker {
public static String post(String url, Map<Object, Object> postMap) {
HttpURLConnection con = null;
try {
con = (HttpURLConnection) new URL(url).openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setConnectTimeout(5000);
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Connection","Keep-Alive");
try(PrintStream ps = new PrintStream(con.getOutputStream())) {
boolean first = true;
for(Map.Entry<Object, Object> post : postMap.entrySet()) {
String key = URLEncoder.encode(""+post.getKey(), "UTF-8");
String value = URLEncoder.encode(""+post.getValue(), "UTF-8");
ps.print((first ? "" : "&") + key + "=" + value);
first = false;
}
}
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
StringBuilder response = new StringBuilder();
String line;
while((line = br.readLine()) != null)
response.append(line);
return response.toString();
}
} catch(IOException e) {
e.printStackTrace();
return null;
} finally {
if(con != null)
con.disconnect();
}
}
public static String post(String url, byte[] data) {
HttpURLConnection con = null;
try {
con = (HttpURLConnection) new URL(url).openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setConnectTimeout(5000);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Connection","Keep-Alive");
con.setRequestProperty("Content-Length", Integer.toString(data.length));
try(DataOutputStream out = new DataOutputStream(con.getOutputStream())) {
out.write(data);
}
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
StringBuilder response = new StringBuilder();
String line;
while((line = br.readLine()) != null)
response.append(line);
return response.toString();
}
} catch(IOException e) {
e.printStackTrace();
return null;
} finally {
if(con != null)
con.disconnect();
}
}
public static String postArray(String url, Map<Object, Object> map) {
return post(url, JsonUtils.toJson(map).getBytes());
}
}
Above is the java code which uses the HTTPurlconnection.
127.0.0.1 - - [13/Aug/2020:19:06:22 -0400] "POST /extra/xenforo/index.php HTTP/1.1" 500 1794 "-" "Mozilla/5.0"
Above is what the apache access.log posts.
My friend hosts the same server same files and has no problem connecting.
I'd also like to note i'm using Xampp to host the forum files not sure if that effects anything.
Thanks if anybody can help :)

Malformed request exception when trying to send GET request

I'm trying to connect to GDAX using their REST API.
I first want to do something very simple, i.e. getting historic rates.
I tried this:
private static final String GDAX_URL = "https://api.gdax.com";
public String getCandles(final String productId, final int granularity) {
HttpsURLConnection connection = null;
String path = "/products/" + productId + "/candles";
try {
//Create connection
URL url = new URL(GDAX_URL);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("granularity", String.valueOf(granularity));
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(path);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
But I get a 400 code in return "Bad Request – Invalid request format".
My problem is with the passing of the path "/products//candles" and the parameters (e.g. granularity).
I don't understand what should go in the request properties and in the message itself, and in what form.
I managed to make it work like this:
URL url = new URL(GDAX_URL + path + "?granularity="+granularity);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
Not sure how to use the DataOutputStream, so I just removed it. At least it works.

Not able to get Jsonstring from this link

String fileURL="https://tools.keycdn.com/geo.json?host=192.168.6.9";
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
System.out.println(responseCode);
Full code:
try {
String url = "http://tools.keycdn.com/geo.json?host=192.168.6.9";
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setInstanceFollowRedirects(true);
HttpURLConnection.setFollowRedirects(true);
conn.setReadTimeout(5000);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
System.out.println("Request URL ... " + url);
boolean redirect = false;
// normally, 3xx is redirect
int status = conn.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
System.out.println("Response Code ... " + status);
if (redirect) {
// get redirect url from "location" header field
String newUrl =conn.getHeaderField("Location");
newUrl=newUrl.replace("https://", "http://");
// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
// open the new connnection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
System.out.println("Redirect to URL : " + newUrl);
}
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer html = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();
System.out.println("URL Content... \n" + html.toString());
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
OUTPUT:
Request URL ... http://tools.keycdn.com/geo.json?host=192.168.6.9
Response Code ... 301
Redirect to URL : http://tools.keycdn.com/geo.json?host=192.168.6.9
URL Content...
301 Moved Permanently301 Moved Permanentlynginx
Done
Iam not able to get json from this link, It gives 301 response code, I tried to get the redirected URL from HTTP header part, eventhough, It returns same URL and same 301 response code, please give java code solution to get JSON string from this URL.
Try this :
String fileURL="https://tools.keycdn.com/geo.json?host=192.168.6.9";
URL url;
try
{
final String USER_AGENT = "Mozilla/5.0";
url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// optional default is GET
httpConn.setRequestMethod("GET");
//add request header
httpConn.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = httpConn.getResponseCode();
System.out.println(responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
catch (Exception e)
{
e.printStackTrace();
}

Connection timed out only for wikmedia api on server but works on local

Following piece of code was working for the last three years, but all of a sudden it throws connection timed out only in server, but works as intended in localhost.
Any comments ?
public String getWikiContent(String query) {
StringBuilder builder = new StringBuilder();
String path = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=1&explaintext=1&titles=" + query + "&format=json&redirects";
try {
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestProperty("Content-Type",
"application/json");
if (urlConn.getResponseCode() != 200) {
throw new IOException(urlConn.getResponseMessage());
}
InputStream is = urlConn.getInputStream();
BufferedReader buff = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = buff.readLine()) != null) {
builder.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
return builder.toString();
}
For some reasons its a network issue, just adding a proxy server fixed it.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url,port));
URLConnection urlConn = url.openConnection(proxy);

Sending post request to https

I need to send a post request to a https address. I have a function that sends post messages currectly but i cant seem to make it work for https.
public static String serverCall(String link, String data){
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = data;
try
{
url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after process will be stored in response variable.
response = sb.toString();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
return response;
}
i have tryed using HttpsURLConnection insted of HttpURLConnection, i am still getting null from my server.
you should call connect();
....
connection.setRequestMethod("POST");
connection.connect();
....

Categories