我正在使用HttpUrlConnection来使用REST服务。当我执行GET时,就像我在下面显示的那样,我不想获得char返回char的信息。我想以返回的格式获得结果。在这里,例如,我想得到一个布尔值,而不是System.out.print((char) ch);
。我该怎么收到它?
我知道我可以将String解析为布尔类型,但是如果我收到另一种数据类型?
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();
}
}
}
}
答案 0 :(得分:1)
我会使用BufferedReader
:它允许逐行读取InputStream
,并且您可能能够以这种方式解析数据。
如果您的数据采用XML或JSON等预定义格式,那么最好使用库来解析您的响应数据。
答案 1 :(得分:1)
您可能希望查看使用DataInputStream。您可以使用此类的readBoolean方法读取布尔值。
DataInputStream和DataOutputStream还为您提供了编写和读取特定数据类型的方法,例如int,float,long等
你应该在发送数据的另一端编写类DataOutputStream的writeBoolean。
代码看起来像下面一样:
InputStream inStrm = urlConnection.getInputStream();
DataInputStream doi = new DataInputStream(inStrm);
boolean bol = doi.readBoolean();
doi.close();
inStrm.close();