我正在开发一款Ipad应用。我必须使用POST方法向Java服务器发送请求,然后,Java服务器将生成bufferedimage的输出流。如何使用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")){....}
答案 0 :(得分: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;
并且您的班级必须符合NSURLConnectionDataDelegate
和NSURLConnectionDelegate
协议。