I started bitnami's iso on vmware machine.
Standard administration login and pass for bitnami is :
login: user,
pass: bitnami.
In Authentication tab is selected Authentication required, Enable REST web service and enable JSONP support.
Any body knows, why I get below statement?
For any help i will be very grateful.
I got a statement :
Exception in thread "main" java.lang.RuntimeException: Failed : HTTP
error code : 401 at NetClientGet.main(NetClientGet.java:36)
Java Result: 1
My code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientGet {
public static void main(String[] args) {
try {
URL url = new URL("http://192.168.0.78/issues.json?key=pjxjDvD9ez0Qm97iApka");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
An HTTP status code 401 means you have an authentication problem. That has nothing to do with your code.
However throwing a RuntimeException for a bad status code is rough.
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
Maybe you can handle different scenarios gracefully. Example :
if (conn.getResponseCode() >= 300) {
// Something unexpected happened
System.out.println("Unexpected response from server");
return // Stop here
}
EDIT
Sorry, I did not read your code carefully. Given the status code you get, it seems you need to send an HTTP auth to your server. It would look like that :
String username = "user"
String password = "bitnami"
String userPassword = username + ":" + password;
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
URL url = new URL("http://192.168.0.78/issues.json?key=pjxjDvD9ez0Qm97iApka");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Basic " + encoding);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
Note : No promise that it will compile/work :)
Code taken from this SO thread : "How to handle HTTP authentication using HttpURLConnection?"
Related
I want to make some searches in spotify database only for learning purpose of rest app.
I'm stuck on the first point of
https://developer.spotify.com/documentation/general/guides/authorization-guide/
Authorization Code Flow
to login in spotify with java app:
package spotify;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/*
1) https://developer.spotify.com/dashboard/applications
*/
public class SpotifyMain {
static final String CLIENTID = "blablablablablablablabla";
static final String CLIENTSECRET = "blablablablablablablabla";
static final String REDIRECTURL = "https://github.com/blablablablablablablabla"; //whiltelisted set inside spotify
public static void main(String[] args) {
try {
String url_auth =
"https://accounts.spotify.com/authorize?"
+ "client_id="+CLIENTID+"&"
+ "response_type=code&"
+ "redirect_uri="+REDIRECTURL+"&"
+ "scope=user-read-private%20user-read-email&"
+ "state=34fFs29kd09";
System.out.println(url_auth);
URL url = new URL(url_auth);
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;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I get error 406.
The url I think is correct because if I put that url inside a browser it displays correctly that the app want to access some resources.
If I put that url inside postman the error changes in 400 bad request...
Am I missing something?
thanks
Try removing this line:
conn.setRequestProperty("Accept", "application/json");
HTTP 406 Error is "Not Acceptable" meaning the server has generated a reply that it can't return as the requested Accept content type.
You are trying to open a webpage (HTML) via code and you set
conn.setRequestProperty("Accept", "application/json");
This will not work for auth. You should open the link in the browser, let the user sign in and take the code from the redirect url.
I am getting
Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 401 at jasonreader.main(jasonreader.java:21)
while executing below code, I am trying to GET data from rest API.
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 jasonreader {
// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) {
try {
URL url = new URL(" https://api.linkedin.com/v1/companies/1337/updates?start=20&count=10&format=json");
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;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Doing this request with Postman, I got this body:
{
"errorCode": 0,
"message": "Unknown authentication scheme",
"requestId": "JP2QSQXZTG",
"status": 401,
"timestamp": 1469513993009
}
That means that you need access token. Please refer to this link for more info or Linkedin documentation
The requirement is to validate whether zip code really exists or not in a specific country??
Country = US
State = California
I wants to know how to call geonames API using REST to get country code by zip code? I would prefer an output in a JSON format over XML.
Answer :
Refer
http://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/
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 NetClientGet {
// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) {
try {
URL url = new URL("http://api.geonames.org/postalCodeSearchJSON?postalcode=94536&maxRows=1&username=demo&country=US");
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;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks Mkyong!
They have a file a country info file,There are regexes for about 150 countries.
You need to create GeoNames model. This model will handle creating, storing, and returning the value of our GeoNames WebServices request.
For more info - http://www.geonames.org/export/web-services.html
i want to get also the email from https://www.googleapis.com/plus/v1/people/me call. I receive a lots of informations, but not the email. Can anyone help?
HttpGet request = new HttpGet("https://www.googleapis.com/plus/v1/people/me?scope=https://www.googleapis.com/auth/userinfo.email");
request.setHeader("Authorization", "Bearer <access_token>");
HttpResponse response = client.execute(request);
EDIT: Updated as part of the improved Google+ Sign-In options in December 2013 - you now can get the email address with the Google+ profile response.
You will get the email from this endpoint as long as you have the email or https://www.googleapis.com/auth/plus.profile.emails.read scopes. See https://developers.google.com/+/web/people/#retrieve_an_authenticated_users_email_address for details.
var request = gapi.client.plus.people.get( {'userId' : 'me'} );
request.execute(function(person) {
if(person['emails']) {
console.log(person['emails'][0].value);
}
});
I found the answer.
My aim was also this.
And We can do it successfully :)
U need:
https://www.googleapis.com/auth/userinfo.email consent
accessToken
and after above two just make HTTP GET request to https://www.googleapis.com/oauth2/v2/userinfo
BUT with added header "Authorization: Bearer <accessToken>"
U can do it by many ways.
My way is customised REST call
package com.google.plus.samples.photohunt.custom;
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 NetClientGet {
// http://localhost:8080/RESTfulExample/json/product/get
public static void makeRequest(String access_token) {
try {
URL url = new URL("https://www.googleapis.com/oauth2/v2/userinfo");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Bearer "+access_token);
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;
System.out.println("REST call made. Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have something I am trying to achieve.
I have a web application running on my localhost on port 8080.
I have a HTTP Server running on localhost:9005.
I have a JSP form that passes info to a servlet java class, that in turn performs the HTTP post to the URL on the HTTP Server localhost:9010 with the data string.
What I need to do is perform the POST and GET as part of the same connection. I have them working as two separate calls, but not on the same connection. It needs to be the same connection, as I post data, the HTTP Server takes this data, processes it and outputs unique data to this URL. Therefore the GET needs to be part of the same connection as he POST.
Can anyone please help?
This is my Process Request java code:
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.List;
import java.util.Map.Entry;
public class ProcessRequest {
public void sendRequestToGateway() throws Throwable{
String message = URLEncoder.encode("OP1387927", "UTF-8");
try {
URL url = new URL("http://localhost:9005/json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("operator=" + message);
writer.close();
System.out.println("connection.getResponseCode() : " + connection.getResponseCode());
System.out.println("connection.getResponseMessage()" + connection.getResponseMessage());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
receiveMessageFromGateway();
} else {
// Server returned HTTP error code.
}
//receiveMessageFromGateway();
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
}
public void receiveMessageFromGateway() throws Throwable {
HttpURLConnection client = null;
OutputStreamWriter wr = null;
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
try {
URL url = new URL("http://localhost:9005/json");
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("GET");
client.setDoOutput(true);
client.setReadTimeout(10000);
client.connect();
System.out.println(" *** headers ***");
for (Entry<String, List<String>> headernew : client.getHeaderFields().entrySet()) {
System.out.println(headernew.getKey() + "=" + headernew.getValue());
}
System.out.println(" \n\n*** Body ***");
rd = new BufferedReader(new InputStreamReader(client.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
System.out.println("body=" + sb.toString());
} finally {
client.disconnect();
rd = null;
sb = null;
wr = null;
}
}
}
Why don't you just return the result from the original POST?
In general you can't control connection reuse with HttpUrlConnection. You might be able to cast your connection to the specific implementation class and interfere with it but that's a horribly unstable way of doing it.
Apache HttpClient is probably a better option, given the requirements.
You can use Apache HTTP Client for this. Its very simple.
If you are using maven, just add the following lines into your POM file:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.3</version>
</dependency>
In this example, I'm submitting a POST request and after that a GET request.
Take a look:
public static String get(String p_url) throws IOException
{
CloseableHttpClient httpclient = HttpClients.createDefault();
// First request: POST
HttpPost httpPost = new HttpPost("http://the-api-url.com/Login/Auth&token=12345"));
CloseableHttpResponse response_post = httpclient.execute(httpPost);
System.out.println(response_post.getStatusLine());
HttpEntity entity_post = response_post.getEntity();
System.out.println(EntityUtils.toString(entity_post));
// Second request: GET
HttpGet httpGet = new HttpGet(p_url);
CloseableHttpResponse response_get = httpclient.execute(httpGet);
System.out.println(response_get.getStatusLine());
HttpEntity entity_get = response_get.getEntity();
System.out.println(EntityUtils.toString(entity_get));
response_post.close();
response_get.close();
return EntityUtils.toString(entity_get);
}