Weird behavior with GET and substring - java

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.

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;
}

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);
}

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);
}

JAVA HTTPS get JSON from URL

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();

Read url content into a String

I am reading the contents of buffered reader in the below method:
public static String readBuffer(Reader reader, int limit) throws IOException
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < limit; i++) {
int c = reader.read();
if (c == -1) {
return ((sb.length() > 0) ? sb.toString() : null);
}
if (((char) c == '\n') || ((char) c == '\r')) {
break;
}
sb.append((char) c);
}
return sb.toString();
}
I am invoking this method later to test -
URL url = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer sb = new StringBuffer();
String line=null;
while((line=readBuffer(in, 2048))!=null) {
sb.append(line);
}
System.out.println(sb.toString());
My question here is, I am returning the contents of bufferedreader into a string in my first method, and appending these String contents into a StringBuffer again in the second method, and reading out of it. Is this the right way? Any other way I can read the String contents that has contents from url?Please advise.
I hope this works -
public static String readFromURL(){
URL url = new URL("http://www.oracle.com/");
StringBuilder responseBuilder = new StringBuilder();
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
int resCode = httpCon.getResponseCode();
InputStream is = null;
if (resCode == 200) {
is = httpCon.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String response = null;
while (true) {
response = reader.readLine();
if (response == null)
break;
responseBuilder.append(response);
}
}
return responseBuilder.toString();
}

Categories