有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何解码从服务器返回的mulitpart?

现在,我的服务器端代码响应一个多部分对象,如下所示(使用ApacheWinkforREST服务):

@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();
    }
}

然后我尝试从输入流中逐个读取字节[]字符,并获得正确的内容。但问题是我不能用这种方法得到像地图一样复杂的物体


共 (0) 个答案