Try with resource for both inputstream and errorstream - java

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

Related

How to handle CWE-400-Resource exhaustion error

We are getting an IBM APPSCAN exception for the following code.
{
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
Can someone suggest a way to handle the same.
I myself have figured out the solution for this.
Just we need to limit the character read by readline().
there is no way to limit the same, so we need to use BoundedBufferedReader.
Try the below:
{
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
}
StringBuilder sb = new StringBuilder();
String line;
BoundedBufferedReader boundedReader = new BoundedBufferedReader(br,204800,204800);
while (( line = boundedReader.readLine() ) != null) {
sb.append(line+"\n");
}
br.close();

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

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