piguy piguy - 4 years ago 114
Java Question

URL JSON String Basic Authentification

I am using this (working) code to connect to a URL, using a proxy and basic authentification. Behind the URL is a JSON String I want to work with - how do I access this JSON String?

package package;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;

import sun.misc.BASE64Encoder;

@SuppressWarnings("restriction")
public class javahttptojson {

public static void main(String[] args) throws IOException, JSONException {

System.setProperty("https.proxyHost", "someIP");
System.setProperty("https.proxyPort", "somePort");

BASE64Encoder encoder = new BASE64Encoder();
String authString = "admin" + ":" + "adminPW";
String authStringEncoded = encoder.encode(authString.getBytes());

URL myURL = new URL("https://URL");
HttpURLConnection is = (HttpURLConnection) myURL.openConnection();

is.setRequestProperty("Authorization", "Basic " + authStringEncoded);

}
}


EDIT (working solution) thanks @ freedev:

StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is.getInputStream()));
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
String result = sb.toString();

System.out.println(result);

Answer Source

The object is have a method getInputStream()

Returns an input stream that reads from this open connection.

BufferedReader br = new BufferedReader(new InputStreamReader(is.getInputStream()));
StringBuilder sb = new StringBuilder();
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
    sb.append(inputLine);
}
String result = sb.toString();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download