I would like a Send an authentication request to Google.
But I get the error: Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL.
Can someone help me and say where the error lies?
My code looks as follows:
public class Main
{
public static void main( String... args ) throws Exception
{
String httpsURL ="\n" +
" client_id=xxx.apps.googleusercontent.com&\n" +
" response_type=code&\n" + // "code" is an Basic Value
" scope=openid%20email&\n" +
" redirect_uri=http://localhost&\n" +
" state=security_token%3D138r5719ru3e1%26url%3Dhttps://oauth2-login-demo.example.com/myHome&\n" +
" login_hint=peterpan#googlemail.com\n";
String inputLine;
String httpsencode ="https://accounts.google.com/o/oauth2/v2/auth?" + URLEncoder.encode(httpsURL, "UTF-8");
URL u = new URL(httpsencode);
HttpsURLConnection con = (HttpsURLConnection)u.openConnection();
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
}
in.close();
}
}
Try to remove all yours "\n" in httpsURL.
You don't need new line char between 2 GET arguments.
Edit : http error code 400 explained here : http://www.checkupdown.com/status/E400.html
Related
I am creating a Java Rest api to create users on Google Duo admin. I am following the documentation https://duo.com/docs/adminapi and I have added auth and date/time header but still I am getting unauthorised error 401. Can anyone guide me what am I doing wrong I have read the doc and added all the mandatory headers.
public static void POSTRequest() throws IOException {
String userCredentials = "Username:Password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));
String dateTime = OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME);
String POST_PARAMS = "{\n" + "\"userId\": 101,\r\n" +
" \"id\": 101,\r\n" +
" \"title\": \"Test Title\",\r\n" +
" \"body\": \"Test Body\"" + "\n}";
URL obj = new URL("https://api-e9770554.duosecurity.com");
HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("Content-Type", "application/json");
postConnection.setRequestProperty("Authorization", basicAuth);
postConnection.setRequestProperty("Date", dateTime);
postConnection.setDoOutput(true);
OutputStream os = postConnection.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = postConnection.getResponseCode();
System.out.println("POST Response Code : " + responseCode);
System.out.println("POST Response Message : " + postConnection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_CREATED) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
postConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST NOT WORKED");
}
}
Error:
{
"code": 40101,
"message": "Missing request credentials",
"stat": "FAIL"
}
Response code: 401 (Unauthorized); Time: 2022ms; Content length: 73 bytes
I want to use the MailChimp api to add a subscriber. As a start, want to read from one of the REST I'm trying to get a response back from the MailChimp api.
I seem to be doing the authorization correctly as I'm getting status 200, but for some reason, I am not getting the response.
Here is the code so far:
public void doPostAction() throws IOException{
// BASIC Authentication
String name = "user";
String password = apikey;
String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL urlConnector = new URL(url);
HttpURLConnection httpConnection = (HttpURLConnection) urlConnector.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
httpConnection.setRequestProperty("Accept", "application/json");
httpConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = httpConnection.getInputStream();
// check status
System.out.println("DoPost: status: " + httpConnection.getResponseCode());
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println("DoPost response: \n" + line);
br.close();
}
Looking at the MailChimp playground, it seems like I'm missing out on a lot...
How do I get the response?
****/ EDIT /****
If anyone's looking at the above code, the output should be:
System.out.println("DoPost response: \n" + sb); // not line
OK, the above code works. Basic error.
I was examining the line variable when it was null, not the response...
When I change to:
System.out.println("DoPost response: \n" + line); // not line
System.out.println("DoPost response: \n" + sb); // but sb StringBuilder
...it works.
I'm writing a Java application that communicates with the NASA open apis. I've a class named NASAClient which exposes the required interface to achieve this task, but I'm facing with the following problem when dealing with the Earth Imagery API.
public EarthImageryResponseObject earthImagery(double lon, double lat, String year, String mon, String day, boolean cloud_score) {
String cs;
if(cloud_score) cs = "True";
else cs = "False";
String url = "https://api.nasa.gov/planetary/earth/imagery?lon="
+ lon
+ "&lat="
+ lat
+ "&date="
+ year+"-"+mon+"-"+day
+ "&cloud_score="
+ cs
+ "&api_key=" + api_key;
try {
String json = (read(getConnection(url)));
return gson.fromJson(json, EarthImageryResponseObject.class);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private String read(HttpURLConnection conn) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
return readFromBufferedReader(br);
}
private String readFromBufferedReader(BufferedReader br) throws IOException {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
return sb.toString();
}
private HttpURLConnection getConnection(String url) throws IOException {
HttpURLConnection connection;
connection = createConnection(url);
this.availability = connection.getHeaderField("X-RateLimit-Remaining");
connection.setConnectTimeout(2000);
this.last_resp = connection.getResponseCode();
return connection;
}
private HttpURLConnection createConnection(String url) throws IOException {
URL UniformResourceLocation = new URL(url);
return (HttpURLConnection) UniformResourceLocation.openConnection();
}
When I call earthImagery with some standard parameters, I get the following url:
https://api.nasa.gov/planetary/earth/imagery?lon=100.75&lat=1.5&date=2017-01-01&cloud_score=False&api_key=[MY_KEY]
If I navigate to this url using curl or the browser, I get the expected Json serialized object, but when invoked within my application, I get a redirection link (with 301 response code) to an heroku app:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><title>Redirecting...</title><h1>Redirecting...</h1><p>You should be redirected automatically to target URL: http://earth-imagery-api.herokuapp.com/earth/imagery/?lon=100.75&lat=1.5&date=2017-01-01&cloud_score=False. If not click the link.
If I try to open a connection to such link, as explained here ,or open it in a browser it returns an error message (parameters are wrong). Really don't know what I am doing wrong. This strategy is the same for the other API I'm using in the application, and they work. Here it follows the stacktrace
Exception in thread "Thread-1" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
at com.google.gson.Gson.fromJson(Gson.java:927)
at com.google.gson.Gson.fromJson(Gson.java:892)
at com.google.gson.Gson.fromJson(Gson.java:841)
at com.google.gson.Gson.fromJson(Gson.java:813)
at com.alexfoglia.nasaapi.NASAClient.earthImagery(NASAClient.java:151)
at com.alexfoglia.nasaapi.gui.EarthPanel.lambda$2(EarthPanel.java:127)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:215)
... 7 more
And that's because i'm expecting a Json object, but I get a String (html redirect page).
If you want your code to automatically follow redirects then set this flag
connection.setFollowRedirects (true);
https://developer.android.com/reference/java/net/HttpURLConnection.html#setFollowRedirects(boolean)
I solved using both HttpURLConnection and SSLSocket. The first connection obtain the redirect link, that is reached not by another httpurlconnection, instead, a SSLSocket is used to get to this link.
public EarthImageryResponseObject earthImagery(double lon, double lat, String year, String mon, String day, boolean cloud_score) {
String cs;
if(cloud_score) cs = "True";
else cs = "False";
String url = "https://api.nasa.gov/planetary/earth/imagery?lon="
+ lon
+ "&lat="
+ lat
+ "&date="
+ year+"-"+mon+"-"+day
+ "&cloud_score="
+ cs
+ "&api_key=" + api_key;
try {
HttpURLConnection conn = getConnection(url);
String new_url = conn.getHeaderField("Location");
SSLSocketFactory factory =
(SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket socket =
(SSLSocket)factory.createSocket("api.nasa.gov", 443);
socket.startHandshake();
socket.getOutputStream().write(("GET "+new_url+"\n").getBytes());
BufferedReader in = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
StringBuilder sb = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
sb.append(inputLine);
in.close();
socket.close();
String json = sb.toString();
System.out.println(json);
return gson.fromJson(json, EarthImageryResponseObject.class);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I tried the code below:
public class URLUploader {
public static void main(String[] args) throws IOException
{
URL url = new URL("http://77.203.65.164:6011");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
String name = "user";
String password = "password";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write("/var/www/html/kannel/javacode/13569595024298.xml");
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
}
}
But I got the following error:
auth string: optiweb:optiweb
Base64 encoded auth string: b3B0aXdlYjpvcHRpd2Vi
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 500 for URL: 77.203.65.164:6011
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1403)
at URLUploader.main(URLUploader.java:32)
What could be wrong?
First, HTTP Response Code 500 is "Internal Server Error" and has nothing to do with authentication.
Second, the statement
writer.write("/var/www/html/kannel/javacode/13569595024298.xml");
just writes the file's full pathname to the server, not the actual file contents, without even a trailing newline. This is certainly not what the server is expecting, and may be the cause of the 500 response. The request you are building and sending may have other problems as well, but without a detailed API reference for whatever's on the other end of the connection, it will be hard to provide further help.
I have a java servlet class that is performing a GET to a specific URL. I am also passing data as part of the GET.
What I need, is in my HTTP Server code that recieves this data, how do I insert user based response data into the Header back so my calling Java servlet class can read it.
I can read standard response things like .getResponseCode() etc, but I need to insert my own response into the header some how. How can this be done? and how can I read it?
This is my java servlet send class:
public void sendRequest(String data, String sendUrl) throws Throwable{
String messageEncoded = URLEncoder.encode(data, "UTF-8");
String message = URLDecoder.decode(messageEncoded);
System.out.println("messageEncoded : " + messageEncoded);
System.out.println("messageDecoded : " + message);
try {
URL url = new URL(sendUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(message);
writer.close();
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
System.out.println(" *** headers ***");
for (Entry<String, List<String>> headernew : connection.getHeaderFields().entrySet()) {
System.out.println(headernew.getKey() + "=" + headernew.getValue());
}
System.out.println(" \n\n*** Body ***");
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
System.out.println("body=" + sb.toString());
System.out.println("connection.getResponseCode() : " + connection.getResponseCode());
System.out.println("connection.getResponseMessage()" + connection.getResponseMessage());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// Ok
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
System.out.println(this.getClass() + " : MalformedURLException Error occured due to: " + e);
} catch (IOException e) {
System.out.println(this.getClass() + " : IOException Error occured due to: " + e);
}
}