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);
}
Related
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;
}
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);
}
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.
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();
I'm trying to get a json string from a url and my method is returning a null string value when I use this line of code:
String jsonStr = getJsonStringFromURL(url);
Here is the method I'm using:
public static String getJsonStringFromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jsonObject = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch (Exception e) {
return null;
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e) {
return null;
}
return result;
}
I have a url variable used where when I copy and paste the url into a browser it does return and display a json string. Any suggestions or help would be greatly appreciated.
The thing is you assigning value to the result when BufferReader is closed. Thats why you getting the null value.
Instead of assigning result = sb.toString(); outside of the BufferReader assign it before closing it.
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
System.out.println(result);// It will print you the value
is.close();
Hope it helps.