gpt4 book ai didi

java - HttpURLConnection - 返回格式

转载 作者:行者123 更新时间:2023-12-02 07:09:53 30 4
gpt4 key购买 nike

我正在使用 HttpUrlConnection 来使用 REST 服务。当我执行 GET 时,就像下面显示的那样,我不想获取逐个字符返回的信息。我想以返回的格式获得结果。例如,在这里,我想获得一个 boolean 值,而不是类似 System.out.print((char) ch); 的东西。我怎样才能收到它?

我知道我可以将字符串解析为 boolean 类型,但是如果我收到其他数据类型怎么办?

public class SensorGetDoorStatus {

public static void main(String[] args) throws Exception
{
HttpURLConnection urlConnection = null;

try {
String webPage = "http://localhost:8080/LULServices/webresources/services.sensors/doorstatus";
String name = "xxxx";
String password = "xxxx";

Authenticator myAuth = new Authenticator()
{
final String USERNAME = "xxxx";
final String PASSWORD = "xxxxx";

@Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(USERNAME, PASSWORD.toCharArray());
}
};

Authenticator.setDefault(myAuth);

String authString = name + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);

URL urlToRequest = new URL(webPage);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();

urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
System.out.println("Authorization : Basic " + authStringEnc);

urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setReadTimeout(15*1000);
urlConnection.connect();

InputStream inStrm = urlConnection.getInputStream();

int ch;
while (((ch = inStrm.read()) != -1))
System.out.print((char) ch);
inStrm.close();


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("Failure processing URL");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}

}

最佳答案

我会玩 BufferedReader :它允许逐行读取 InputStream,并且您也许能够以这种方式解析数据。

如果您的数据采用 XML 或 JSON 等预定义格式,那么您最好使用库来解析您的响应数据。

关于java - HttpURLConnection - 返回格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15658146/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com