通过网络发布数据不会';不能在java.ioAPI中工作
我有下面的一段代码,在从eclipse运行时可以很好地工作通过网络发布数据不会';不能在java.ioAPI中工作,java,jersey,java-io,Java,Jersey,Java Io,我有下面的一段代码,在从eclipse运行时可以很好地工作 String str = "testing"; InputStream is = new ByteArrayInputStream(str.getBytes()); int length = is.available(); byte[] data = new byte[length]; is.read(data, 0, length); System.out.println("output "+new String(data
String str = "testing";
InputStream is = new ByteArrayInputStream(str.getBytes());
int length = is.available();
byte[] data = new byte[length];
is.read(data, 0, length);
System.out.println("output "+new String(data));
当我破坏这段代码,使用Jerser客户端API通过网络发布数据,并尝试使用Jersey在服务器上读回数据时,我没有得到发布的值。客户端代码如下所示
public static void main(String s[]) throws IOException {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
String str = "testingthi";
InputStream is = new ByteArrayInputStream(str.getBytes());
WebResource webResource = client.resource("http://192.168.1.15:8090/JersySample/resources/stream/upload");
ClientResponse response = webResource.type(MediaType.APPLICATION_OCTET_STREAM).post(ClientResponse.class,is);
is.close();
}
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response upload( InputStream is) {
try{
int size = is.available();
byte data[] = new byte[size];
is.read(data,0,size);
System.out.println(" Posted data is "+ new String(data)+" length is "+size+" stream size "+is.available());
is.close();
}catch (Exception e) {
e.printStackTrace();
}
return Response.ok().entity("Done").build();
}
服务器上的代码如下所示
public static void main(String s[]) throws IOException {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
String str = "testingthi";
InputStream is = new ByteArrayInputStream(str.getBytes());
WebResource webResource = client.resource("http://192.168.1.15:8090/JersySample/resources/stream/upload");
ClientResponse response = webResource.type(MediaType.APPLICATION_OCTET_STREAM).post(ClientResponse.class,is);
is.close();
}
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response upload( InputStream is) {
try{
int size = is.available();
byte data[] = new byte[size];
is.read(data,0,size);
System.out.println(" Posted data is "+ new String(data)+" length is "+size+" stream size "+is.available());
is.close();
}catch (Exception e) {
e.printStackTrace();
}
return Response.ok().entity("Done").build();
}
当我使用ApacheCommonsIOAPI读取字符串时,我确实得到了我发布的字符串值。有人能解释一下为什么在非网络环境下使用java.io API时它不起作用吗?您犯了一个常见的错误,即假设read()填充了缓冲区。它没有义务这么做。请参阅Javadoc。它只能读取至少一个字节并返回。字节计数,返回-1,或引发IOException
您还滥用了available()。它不会返回流中的总字节数,Javadoc中会特别警告您使用它的方式。您不是在“通过网络发布InputStream”。你不能。您正在通过网络发布数据。为什么当我在eclipse中运行数据时它可以工作,而当我在网络上使用相同的api方法时它会失败?