JAVA HTTPS get JSON from URL - java

I'm trying to receive the json of this url: https://usecryptos.com/jsonapi/ticker/BTC-USD It's accessible by browser, however, I haven't been successed, can someone post a code to do it?

I'm trying like this:
public static String getJSON(String url, int timeout) throws IOException {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
return null;
}

For https you should use the HttpsUrlConnection like this:
URL u = new URL("https://blockchain.info/de/ticker");
HttpsURLConnection conn = (HttpsURLConnection) u.openConnection();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String inputLine;
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
}
br.close();
isr.close();
is.close();
conn.disconnect();

Related

How can I raw post using HttpURLConnection

I need to raw post to authorization system.
POST /v1 HTTP/1.1
Host: api.auth.gg
Content-Type: application/x-www-form-urlencoded
Content-Length: 124
type=login&aid=76471&apikey=156444483727231153&secret=aIGeWaR4YHR3LBCvtr4yOtDlb0HI4MA0gBL&username=demo&password=demo&hwid=demo
I tried this code (I used gson to JSON)
public int LoginWithUserPass(String user, String pass) throws Exception {
URL url = new URL("https://api.auth.gg/v1/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "LoginSystem");
con.addRequestProperty("Content-Type", "Content-Type: application/x-www-form-urlencoded");
JsonObject auth = new JsonObject();
auth.addProperty("type", "login");
auth.addProperty("hwid", getHWID());
auth.addProperty("password", pass);
auth.addProperty("username", user);
auth.addProperty("secret", "test");
auth.addProperty("apikey", apikey);
auth.addProperty("aid", "test");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(auth.toString());
wr.flush();
if (con.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(sb.toString());
if (!element.getAsJsonObject().get("result").getAsString().equalsIgnoreCase("failed")) {
System.out.println("Successfully Logged in!");
} else {
System.out.println(element.getAsJsonObject());
return -1;
}
}
return con.getResponseCode();
}
It returns
{"result":"failed","message":"Invalid type"}
Your example shows a query string, not a JSON string. So instead of creating a JSON object simply write your parameters to the stream.
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.append("type").append("=").append("login");
wr.append("&").append("hwid").append("=").append(getHWID());
...
Fixed with this
public String loginWithUserPass(String user, String pass) throws Exception {
String url = "https://api.auth.gg/v1/", charset = StandardCharsets.UTF_8.name();
String hwid = getHWID(), secret = "*secret*", aid = "*aid*";
String query = String.format("type=login&hwid=%s&password=%s&username=%s&secret=%s&apikey=%s&aid=%s",
URLEncoder.encode(hwid, charset),
URLEncoder.encode(pass, charset),
URLEncoder.encode(user, charset),
URLEncoder.encode(secret, charset),
URLEncoder.encode(apikey, charset),
URLEncoder.encode(aid, charset));
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("User-Agent", "LoginSystem");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(query.getBytes(charset));
}
InputStream response = connection.getInputStream();
if (connection.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(response));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(sb.toString());
return element.getAsJsonObject().get("result").getAsString();
}
return null;
}

http post request return 401 when the auth credential are correct -

I'm having this issue for posting data only, I got 401 (non-authorized) while my credential are correct! how to fix this?
ttpURLConnection urlConnection;
IgnoreSSL();
String url = null;
url = "http://" + nmap_node.getHost() + ":"+nmap_node.getPort() + "/post";
String result = null;
try {
String userpass = user_name + ":" + password; //stored in the class
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
//Connect
urlConnection = (HttpURLConnection) ((new URL(url).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "Basic "+basicAuth);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(10000);
urlConnection.connect();
//data
String data = datajson.toString(); //method return json to use
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
int responseCode=urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
}else {
// return new String("false : "+responseCode);
new String("false : "+responseCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I tried in Linux with curl command It works perfectly - I got respond 200 and printed results in the screen.

Try with resource for both inputstream and errorstream

How can I use try with resource to cover all corners when it comes to getInputStream and getErrorStream
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
BufferedReader bufferedReader;
if(connection.getResponseCode() == 200) {
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
bufferedReader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
String line;
StringBuilder result = new StringBuilder();
while((line = bufferedReader.readLine()) != null) {result.append(line);}
bufferedReader.close();
if(connection.getResponseCode() != 200) {
throw new Gson().fromJson(result.toString(), FooException.class);
} else {
return new Gson().fromJson(result.toString(), Foo.class);
}
If I understand your question, then you might use a ternary operator ? : to construct your BufferedReader in a try-with-resources. Also, I'd save the responseCode to a local variable. Something like,
StringBuilder result = new StringBuilder();
int responseCode = connection.getResponseCode();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
responseCode == 200 ? connection.getInputStream()
: connection.getErrorStream()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
}
if (responseCode != 200) {
throw new Gson().fromJson(result.toString(), FooException.class);
} else {
return new Gson().fromJson(result.toString(), Foo.class);
}

Weird behavior with GET and substring

So I made this piece of code:
options = getURL("http://florens.be/EnterRoomAlert/options.txt");
soundOptionStartPos = options.indexOf("sound") + 6;
soundOptionEndPos = options.indexOf("e", soundOptionStartPos) + 1;
soundOptionResult = options.substring(soundOptionStartPos, soundOptionEndPos);
And this is the getURL method:
public static String getURL(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
This is the content off the file options.txt:
sound=false
mail=false
database=false
Everytime I run this code and print out soundOptionResult I get true.

how to get content even if we have error code response

I create HTTP GET like this:
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
Work great! But Imagine that server return error 201 or error 206. How to get content of response even error code is not 200? I do not want to use another library, I want to do this using HttpURLConnection
BufferedReader rd = null;
if (urlConnection.getResponseCode() == 200) {
rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
} else {
rd = new BufferedReader(new InputStreamReader(urlConnection.getErrorStream()));
}
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}

Categories