现在我的服务器端代码响应了一个多部分对象(使用Apache Wink for REST服务):
@Path(value = "/multipart")
@GET
@Produces("multipart/mixed;boundary=myboundary")
public BufferedOutMultiPart processMessage() {
BufferedOutMultiPart mpout = new BufferedOutMultiPart();
mpout.setBoundary("myboundary");
/* first part */
OutPart op = new OutPart();
op.setBody("Hello world");
op.setContentType("text/plain");
op.addHeader("MyCustomHeader", "ThisIsTheGreetingPart");
mpout.addPart(op);
/* second part */
op = new OutPart();
byte[] binaryData = "Bonjour".getBytes();
op.setBody(binaryData);
op.setContentType("custom/binarytype");
mpout.addPart(op);
return mpout;
}
我试着像这样解码它:
@Test
public void test() throws ClassNotFoundException {
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(
"http://DongyangLuo-PC.cn.ibm.com:9080/Cloud_Modeler/datasource/multipart");
try {
int statusCode = client.executeMethod(get);
if (statusCode == 200) {
// I instantiate the parser and try to instantiate the
// InMultiPart object with the parser
MultiPartParser parser = new MultiPartParser(
get.getResponseBodyAsStream(), "myboundary");
InMultiPart ins = new InMultiPart(parser);
InPart part = ins.next();
System.out.println("The content type is: "
+ part.getContentType());
InputStream input = part.getInputStream();
// this kind of decoding will get java.io.StreamCorruptedException: invalid stream header: 48656C6C
byte[] ba = (byte[]) new ObjectInputStream(input).readObject();
for(int j = 0; j < ba.length; j++){
System.out.print(ba[j] + "\t");
}
System.out.println("The content body is: "
+ part.getBody(String.class, String.class));
System.out.println("The content headers are: "
+ part.getHeaders());
part = ins.next();
// this kind of decoding doesn't work because of losing a provider which shouldn't appear in client.
byte[] body = part.getBody(byte[].class, byte[].class);
System.out.println(part.getHeaders());
System.out.println(part.getContentType());
System.out.println(body);
assertEquals("Bonjour", new String(body));
} else {
System.out.println(statusCode);
}
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
然后我尝试从输入流中逐个读取byte []字符并获得正确的内容。但问题是我不能像Map对象那样得到一些复杂的对象。