2

我正在开发一个 Ipad 应用程序。我必须使用 POST 方法向 Java 服务器发送请求,然后,Java 服务器将产生一个缓冲图像的输出流。如何使用objective-c接收这个缓冲图像?

POST 方法的代码:

NSURL * url = [NSURL URLWithString:urlString];
_request = [NSMutableURLRequest requestWithURL:url];

[_request setHTTPMethod:@"POST"];
[_request setValue:[NSString stringWithFormat:cmdString] forHTTPHeaderField:@"cmd"];
[_request setValue:[NSString stringWithFormat:paramString] forHTTPHeaderField:@"param"];

[NSURLConnection connectionWithRequest:_request delegate:self];

Java服务器的代码:

    OutputStream os=http.getResponseBody();
    String cmd=http.getRequestHeaders().getFirst("cmd");
    int cnt=Integer.valueOf(http.getRequestHeaders().getFirst("param"));
    System.out.println(cmd+"   "+cnt);
    int w,h;
    http.sendResponseHeaders(200,0);
    if(cmd.equals("1"))
    {
        w=512;
        h=512;
        idlmanager idl=new idlmanager();
        idl.createObject();
        byte[] buf=new byte[w*h*3+1];
        JIDLArray idlBuf=new JIDLArray(buf);
        JIDLNumber r=idl.UPDATEIMAGE(idlBuf,new JIDLInteger(1), new JIDLInteger(cnt));
        buf=(byte[]) idlBuf.arrayValue();
        int i,j;
        int[] data =new int[w*h];
        for(i=0;i<w*h;i++)
        {           
            data[i]=((buf[i*3]+256)%256)*256*256+((buf[i*3+1]+256)%256)*256+(buf[i*3+2]+256)%256;
        }

        int[] mask={255*256*256,255*256,255};
        ColorModel cm=new DirectColorModel(24,255*256*256 , 255*256,255);
        SampleModel sm=new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT,w,h,mask);          
        DataBuffer db = new DataBufferInt(data, w*h);
        WritableRaster rast=Raster.createWritableRaster(sm,db, new Point(0,0));

        BufferedImage bufImg= new BufferedImage(cm, rast, false, null);
        ImageIO.write(bufImg, "png", os);
    }else if(cmd.equals("2")){....}
4

1 回答 1

1

最简单的方法是使用来自 NSURLConnection的sendSynchronousRequest:returningResponse:error:。

__autoreleasing NSError *error = nil;
__autoreleasing NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
[responseData writeToFile:savePath atomically:YES];

假设savePath一个 NSString 包含一个有效的路径。

如果您想使用connectionWithRequest:delegate:如代码中所述,则必须实现以下委托方法:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Error: %d %@", [error code], [error localizedDescription]);
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    responseData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [responseData writeToFile:savePath atomically:YES]; 
}

这里 responseData 是一个声明的实例变量:

NSMutableData *responseData;

并且您的课程必须符合NSURLConnectionDataDelegateandNSURLConnectionDelegate协议。

于 2012-11-27T03:43:12.033 回答