將 `UITextField` 的輸入內容動態拼接到 POST 請求體字符串中,替換硬編碼的參數值。
- (IBAction)signin:(id)sender {
// 1. 獲取輸入框文本
NSString *username = self.username.text; // IBOutlet 連接的 UITextField
NSString *password = self.pwd.text;
// 2. 基礎參數校驗 (防空指針、長度限制等)
if (!username.length || !password.length) {
// 提示用戶輸入完整
return;
}
// 3. 構建請求 URL (注意:原 URL 含 jsoncallback=? 疑似 JSONP,POST 請求通常不需此參數)
NSURL *url = [NSURL URLWithString:@"https://14.17.84.128:8088/wcf/ActionService.svc/action/web/get/do"];
// 建議去掉 ?jsoncallback=?,或確認服務端確實需要
// 4. 創建可變請求
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; // 關鍵!
// 5. 動態拼接參數字符串 (使用 stringWithFormat)
// 注意:原參數格式 "ActionCode =0x2001¶meter=pwd###123#####userNo###aaa& LoginID=&LoginIp="
// 空格可能導致解析異常,建議去除鍵值對中的空格
NSString *bodyString = [NSString stringWithFormat:
@"ActionCode=0x2001¶meter=pwd###%@#####userNo###%@&LoginID=&LoginIp=",
password, username]; // 順序對應原偽代碼:pwd=密碼, userNo=用戶名
// 6. 設置 HTTP Body (UTF-8 編碼)
NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyData];
// 7. 發送同步請求 (主線程會阻塞,建議生產環境用異步 NSURLSession)
NSURLResponse *response = nil;
NSError *error = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
// 8. 處理響應
if (error) {
NSLog(@"請求失敗: %@", error.localizedDescription);
return;
}
if (receivedData) {
NSString *responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(@"響應: %@", responseString);
// 解析 JSON/XML 並更新 UI
}
}
// 使用 NSURLSession 異步 (iOS 7+)
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) { NSLog(@"Error: %@", error); return; }
NSString *resp = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Response: %@", resp);
// 回主線程更新 UI
dispatch_async(dispatch_get_main_queue(), ^{
// self.label.text = resp;
});
}];
[task resume];