URL JSON字符串基本身份验证

时间:2017-02-06 14:52:46

标签: java json url

我正在使用此(工作)代码连接到URL,使用代理和基本身份验证。 URL后面是我想要使用的JSON字符串 - 如何访问此JSON字符串?

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

        }
    }

编辑(工作解决方案)感谢@ 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);

1 个答案:

答案 0 :(得分:1)

对象is有一个方法getInputStream()

  

返回从此打开的连接读取的输入流。

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