iOSでHTTP POSTリクエストを送信する
開発中のiOSアプリケーションでHTTPポストを送信しようとしていますが、応答として(urlconnectionから)コード200を取得しても、プッシュがサーバーに到達しません。サーバーから応答を得ることも、サーバーが投稿を検出することもありません(サーバーはAndroidからの投稿を検出します)
ARCを使用していますが、pdとurlConnectionを強力に設定しています。
これはリクエストを送信するための私のコードです
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",dk.baseURL,@"daantest"]]];
[request setHTTPMethod:@"POST"];
[request setValue:@"text/xml"
forHTTPHeaderField:@"Content-type"];
NSString *sendString = @"<data><item>Item 1</item><item>Item 2</item></data>";
[request setValue:[NSString stringWithFormat:@"%d", [sendString length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[sendString dataUsingEncoding:NSUTF8StringEncoding]];
PushDelegate *pushd = [[PushDelegate alloc] init];
pd = pushd;
urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:pd];
[urlConnection start];
これはデリゲートの私のコードです
#import "PushDelegate.h"
@implementation PushDelegate
@synthesize data;
-(id) init
{
if(self = [super init])
{
data = [[NSMutableData alloc]init];
[data setLength:0];
}
return self;
}
- (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten
{
NSLog(@"didwriteData Push");
}
- (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes
{
NSLog(@"connectionDidResumeDownloading Push");
}
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
{
NSLog(@"didfinish Push @Push %@",data);
}
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
NSLog(@"did send body");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.data setLength:0];
NSHTTPURLResponse *resp= (NSHTTPURLResponse *) response;
NSLog(@"got response with status @Push %d",[resp statusCode]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d
{
[self.data appendData:d];
NSLog(@"recieved data @Push %@", data);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];
NSLog(@"didfinishLoading%@",responseText);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error ", @"")
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK", @"")
otherButtonTitles:nil] show];
NSLog(@"failed &Push");
}
// Handle basic authentication challenge if needed
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSLog(@"credentials requested");
NSString *username = @"username";
NSString *password = @"password";
NSURLCredential *credential = [NSURLCredential credentialWithUser:username
password:password
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
@end
コンソールは常に次の行と次の行のみを出力します。
2013-04-01 20:35:04.341 ApprenticeXM[3423:907] did send body
2013-04-01 20:35:04.481 ApprenticeXM[3423:907] got response with status @Push 200
2013-04-01 20:35:04.484 ApprenticeXM[3423:907] didfinish Push @Push <>
次のコードは、POST
name__メソッドを使用した簡単な例を示しています。(POST
name__メソッドでデータを渡す方法)
ここでは、POSTメソッドの使用方法について説明します。
1。実際のユーザー名とパスワードで投稿文字列を設定します。
NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",@"username",@"password"];
2。NSASCIIStringEncoding
name__を使用して投稿文字列をエンコードし、NSData形式で送信する必要がある投稿文字列もエンコードします。
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
データの実際の長さを送信する必要があります。投稿文字列の長さを計算します。
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
。HTTP
name__メソッド、投稿文字列の長さを持つhttpヘッダーフィールドなど、すべてのプロパティを使用してUrlrequestを作成します。 URLRequest
name__オブジェクトを作成して初期化します。
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
そのリクエストにデータを送信するURLを設定します。
[request setURL:[NSURL URLWithString:@"http://www.abcde.com/xyz/login.aspx"]];
次に、HTTP method(POSTまたはGET)を設定します。この行をコードにそのまま記述します。
[request setHTTPMethod:@"POST"];
HTTP
name__ヘッダーフィールドに投稿データの長さを設定します。
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
HTTPヘッダーフィールドのエンコード値も設定します。
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
PostDataでurlrequestのHTTPBody
name__を設定します。
[request setHTTPBody:postData];
4。次に、URLConnectionオブジェクトを作成します。 URLRequestで初期化します。
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
初期化されたURL接続を返し、URLリクエストのデータのロードを開始します。 URL
name__接続が適切に行われているかどうか、または以下のようにif/elseステートメントを使用していないかどうかを確認できます。
if(conn) {
NSLog(@"Connection Successful");
} else {
NSLog(@"Connection could not be made");
}
5。 HTTPリクエストからデータを受信するには、URLConnection Class Referenceが提供するデリゲートメソッドを使用できます。デリゲートメソッドは以下のとおりです。
// This method is used to receive the data which we get using post method.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
// This method receives the error report in case of connection is not made to server.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
// This method is used to process the data after connection has made successfully.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
参照するこれおよびこれドキュメントPOST
name__メソッドの場合。
そして、ソースコード HTTPPost Method。 の最良の例です
ロギングライブラリで使用したメソッドは次のとおりです。 https://github.com/goktugyil/QorumLogs
このメソッドは、Googleフォーム内のhtmlフォームに入力します。 Swiftを使用している人に役立つことを願っています。
var url = NSURL(string: urlstring)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)
-(void)sendingAnHTTPPOSTRequestOniOSWithUserEmailId: (NSString *)emailId withPassword: (NSString *)password{
//Init the NSURLSession with a configuration
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
//Create an URLRequest
NSURL *url = [NSURL URLWithString:@"http://www.example.com/apis/login_api"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
//Create POST Params and add it to HTTPBody
NSString *params = [NSString stringWithFormat:@"email=%@&password=%@",emailId,password];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
//Create task
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",responseDict);
}];
[dataTask resume];
}
理由は確かではありませんが、次の方法をコメントアウトするとすぐに機能します:
connectionDidFinishDownloading:destinationURL:
さらに、ダウンロード情報が必要な場合を除き、NSURLConnectionDataDelegateのメソッドのみがNSUrlConnectionDownloadDelegateプロトコルのメソッドを必要とすると思います。
**パラメータ付きのAPIを投稿し、URLで検証して、json応答キーのステータスが「success」の場合にナビゲートします
NSString *string= [NSString stringWithFormat:@"url?uname=%@&pass=%@&uname_submit=Login",self.txtUsername.text,self.txtPassword.text];
NSLog(@"%@",string);
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(@"responseData: %@", responseData);
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"responseData: %@", str);
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:nil];
NSDictionary* latestLoans = [json objectForKey:@"status"];
NSString *str2=[NSString stringWithFormat:@"%@", latestLoans];
NSString *str3=@"success";
if ([str3 isEqualToString:str2 ])
{
[self performSegueWithIdentifier:@"move" sender:nil];
NSLog(@"successfully.");
}
else
{
UIAlertController *alert= [UIAlertController
alertControllerWithTitle:@"Try Again"
message:@"Username or Password is Incorrect."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){
[self.view endEditing:YES];
}
];
[alert addAction:ok];
[[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor redColor]];
[self presentViewController:alert animated:YES completion:nil];
[self.view endEditing:YES];
}
JSON Response:{"status": "success"、 "user_id": "58"、 "user_name": "dilip"、 "result": "ログインに成功しました"}作業コード
**
IOSでHTTP POSTリクエストを送信する(Objective C):
-(NSString *)postexample{
// SEND POST
NSString *url = [NSString stringWithFormat:@"URL"];
NSString *post = [NSString stringWithFormat:@"param=value"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:url]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;
//RESPONDE DATA
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
if([responseCode statusCode] != 200){
NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]);
return nil;
}
//SEE RESPONSE DATA
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Response" message:[[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}
Swift 3または4を使用すると、サーバー通信のためにこれらのhttp要求にアクセスできます。
// POSTデータを要求する場合
func postAction() {
//declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
let parameters = ["id": 13, "name": "jack"] as [String : Any]
//create the url with URL
let url = URL(string: "www.requestURL.php")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume() }
//リクエストからデータを取得するため
func GetRequest() {
let urlString = URL(string: "http://www.requestURL.php") //change the url
if let url = urlString {
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error ?? "")
} else {
if let responceData = data {
print(responceData) //JSONSerialization
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with:responceData, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
}
}
}
task.resume()
}
}
//リクエストから画像や動画などのダウンロードコンテンツを取得するため
func downloadTask() {
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")
//Create URL to the source file you want to download
let fileURL = URL(string: "http://placehold.it/120x120&text=image1")
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %@", error?.localizedDescription ?? "");
}
}
task.resume()
}