I'm developing an Ipad app. I have to use the POST method to sent request to the Java server, then, the Java server will produce an outputstream of an bufferedimage. How can I receive this bufferedimage using objective-c?
the POST method's code:
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];
the Java server's code:
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")){....}
the easiest way is to use sendSynchronousRequest:returningResponse:error: from NSURLConnection.
__autoreleasing NSError *error = nil;
__autoreleasing NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
[responseData writeToFile:savePath atomically:YES];
Assume savePath
is a NSString contains a valid path.
if you want to use connectionWithRequest:delegate: as mentioned in your code, you will have to implement the following delegate methods:
- (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];
}
here responseData is an instance variable declared with:
NSMutableData *responseData;
and your class must conforms the NSURLConnectionDataDelegate
and NSURLConnectionDelegate
protocols.