我有这个球衣webResource代码:
@Override
public int Foo(long uId, String secretKey, long tileId) {
int answer = 0;
String ans;
try {
ClientResponse response = webResource
// .path("multi-get")
.queryParam("reqtype", "tileBatch")
.queryParam("protocol", "1")
.queryParam("sessionid", String.valueOf(uId))
.queryParam("cookie", String.valueOf(secretKey))
.queryParam("num", "1")
.queryParam("t0", String.valueOf(tileId))
.queryParam("v0", "0")
.get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
String output = response.getEntity(String.class);
answer = response.getEntityInputStream().available();
byte[] byteArray = output.getBytes("UTF-8");
ans = new String(byteArray, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return answer;
}
}
我看到String output = response.getEntity(String.class);
不是空的,但在answer = response.getEntityInputStream().available();
然后answer == 0
是怎么来的?
如果我想将二进制数据中的2个第一个字节解析为整数
我怎样才能做到这一点? (int) byteArray[0]
?
e.g。 00000000-00010000
修改
我试过这段代码:
InputStream entityInputStream = response.getEntityInputStream();
answer = entityInputStream.available();
String output = response.getEntity(String.class);
byte[] byteArray = new byte[2];
// entityInputStream.reset();
entityInputStream.read(byteArray);
String s = new String(byteArray);
但byteArray == {0,0}
即使output
不为空。
output == ....
�*WZDF04x��:w|������6[�!�M���@HH �� �����TQ�W�""$@�Z $(���ұ=��[��� ��d�s�n6K�������{�99��{����$qE48"
我的方法是否正确?
答案 0 :(得分:1)
我看到
String output = response.getEntity(String.class);
不是空的,但在answer = response.getEntityInputStream().available();
然后answer == 0
是怎么来的?
执行response.readEntity(String.class)
时,正在读取输入流,并清除输入流。因此,下次检索输入流的尝试将返回一个空流。
如果我想将二进制数据中的2个第一个字节解析为整数,我该怎么办?
您只需将InputStream
打包在DataInputStream
中,然后使用DataInputStream.readInt()
即可。然后,您可以使用response.readEntity(String.class);
读取其余的输入流。你似乎试图读取字符串,然后 int,它不符合你的上述陈述。
测试
@Path("/string")
public class StringResource {
@GET
public StreamingOutput getString() {
return new StreamingOutput(){
@Override
public void write(OutputStream out)
throws IOException, WebApplicationException {
DataOutputStream outStream = new DataOutputStream(out);
outStream.writeInt(1234567);
outStream.writeUTF("Hello World");
}
};
}
}
@Test
public void testMyResource() throws Exception {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource wr = client
.resource("http://localhost:8080/api/string");
ClientResponse response = wr.get(ClientResponse.class);
InputStream is = response.getEntityInputStream();
DataInputStream dis = new DataInputStream(is);
int num = dis.readInt();
System.out.println(num);
System.out.println(response.getEntity(String.class));
response.close();
}
打印1234567
然后Hello World