I want equivalent method for objective C from JAVA code
public static void post(URL url, byte[] msg, String user, String pass) throws Exception
{
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
开发者_如何学运维 conn.setInstanceFollowRedirects(false);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml");
conn.setRequestProperty("Authorization", "Basic " + makeAuth(user,pass));
//conn.setRequestProperty("Content-Length", msg.length + "");
OutputStream out = conn.getOutputStream();
out.write(msg);
out.flush();
System.out.println("\n*** POST results ***");
InputStream in = conn.getInputStream();
printResults(in);
try {out.close();} catch (Exception whocares) {}
try {in.close();} catch (Exception whocares) {}
}
Here is called the web service where uri is URL for webservice. user and pass is username and password.
Can any one know how to call the same thing in objective c.
You could do it just as easily using foundation classes.
- (void)postUser:(NSString *)user andPass:(NSString *)pass toURL:(NSURL *)url
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[request setHTTPMethod:@"POST"];
[request addValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
[request addValue:[NSString stringWithFormat:@"Basic %@", makeAuth(user, pass)] forHTTPHeaderField:@"Authorization"];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Response from server: %@", responseString);
[responseString release];
}
One approach is to use ASIHTTPRequest (as proposed by 0xJoKe) and implement it like this:
- (void)post:(NSData *)data toURL:(NSURL *)url username:(NSString *)username password:(NSString *) password
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setUsername:username];
[request setPassword:password];
[request addRequestHeader:@"Content-Type" value:@"text/xml"];
[request appendPostData:data];
[request startSynchronous];
NSData *responseData= [request responseData];
// do something with response
}
Note that I've used NSData
instances instead of byte arrays.
A easy to use and very powerful option is the ASIHTTPRequest. To send a POST-request, you should use ASIFormDataRequest which makes it really easy for you to set variables, the username and the password you need to access the server.
精彩评论