【问题标题】:Simple iOS POST http request简单的 iOS POST http 请求
【发布时间】:2014-08-01 15:01:00
【问题描述】:

我希望从 iOS 应用程序向 PHP 文件发出 POST http 请求。我只需要获取一个字段中的值并将其发布到 PHP。 android 版本尚未完成,但至少可以运行,代码如下:

private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

    @Override
    protected Double doInBackground(String... params) {
        // TODO Auto-generated method stub
        postData(params[0]);
        return null;
    }

    protected void onPostExecute(Double result){
        Toast.makeText(getApplicationContext(), "Check In Sent!", Toast.LENGTH_SHORT).show();
    }

    public void postData(String phone) {
        String content = "";
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("MY_URL_HERE");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("phone", phone));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            // Custom code for response
            StatusLine statusLine = response.getStatusLine();
            // Check the HTTP resquest for success
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // toast here
                        Toast.makeText(getApplicationContext(), "Check in Complete", Toast.LENGTH_LONG).show();
                    }
                });
            } else if (statusLine.getStatusCode() == HttpStatus.SC_FORBIDDEN) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // toast here
                        Toast.makeText(getApplicationContext(), "Number already checked in", Toast.LENGTH_LONG).show();
                    }
                });
            } else if (statusLine.getStatusCode() == HttpStatus.SC_BAD_REQUEST); {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // toast here
                        Toast.makeText(getApplicationContext(), "Phone number not found", Toast.LENGTH_LONG).show();
                    }
                });
            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            Log.e("ALFA", "HTTPReq:ClientProtocolException " + e.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e("ALFA", "HTTPReq:IOException " + e.toString());
        }
    }

}

没什么太花哨的,我只是很难在 iOS 中找到如何做到这一点。我找到教程并开始做它们,发现它们已被弃用或错误。谁能帮我弄清楚如何做到这一点的基础知识,或者至少是一个关于我如何做到这一点的非过时教程?顺便说一下,这个应用程序适用于 iOS 7。我需要它将电话号码发布到我拥有的 php 文件中,并且 PHP 文件会根据它是否成功返回状态代码。

所以这就是我到目前为止没有第三方库的情况:

NSString *post = [NSString stringWithFormat:@"&phone=%@",@"phonenumberhere"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"url_here"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
    NSLog(@"Connection Successful");
}
else
{
    NSLog(@"Connection could not be made");
}

现在,如果我检查我的 SQL 数据库,我知道它正在工作并且可以正确发布。但是,我怎样才能看到它返回的状态码呢?

【问题讨论】:

  • 更好的提问方式是发布你的objective-c尝试,否则这个问题看起来像:“请为我翻译我的代码”。
  • 是的,你是对的!我现在将发布我的尝试。在等待答案时,我让它在某种程度上起作用。我现在将编辑我的帖子以包含它

标签: android ios objective-c


【解决方案1】:

我使用AFNetworking library 进行所有http 通信。

post 请求的代码如下所示:

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL: [NSURL URLWithString:BASE_URL]]; // BASE_URL is the web url prefix for example (http://example.com)

NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"param1_value", @"param1_name", @"param2_value", @"param2_name", nil];

// URL_POST for example /post_page.php the end address will be http://example.com/post_page.php
[httpClient postPath:URL_POST parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSLog(@"Login response: %@",operation.responseString);
        //process success response

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //process http errors
}];

【讨论】:

  • 好的,所以我将 AFNetworking 库添加到了一个名为 AFNetworking 的新组中。我收到“使用未声明的标识符”。有什么想法吗?
  • 您是否已将#import 添加到您的源代码中?
  • 哦,这就是我忘记做的事情。感谢您添加该评论。我现在可以在没有库的情况下使用它,但由于我仍在学习应用程序开发,我相信我会在不久的将来使用它!
【解决方案2】:

如果您对使用第三方库不感兴趣(尽管它通常会为您简化工作),那么使用原生 NSURLConnection 应该适合您。

- (void) postRequest
{
    NSString *postString = @"param1=val2&param2=val2";

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"URL"]];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
}

#pragma mark NSURLConnectionDataDelegate Methods
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    //Here handle the error
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //Here you get the meta data of the response
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //Here the actual data you can just add data to an
    //NSMutableData object each time this method is called
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
    //This is called when all the data is received
}

【讨论】:

  • 是的!我在这里找到了这个:panditpakhurde.wordpress.com/2009/04/16/…,它看起来一样,这很棒,因为它有效。如何查看退货状态码?
  • 您可以将- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response中的响应转换为(NSHTTPURLResponse*)并调用[response statusCode]
  • 谢谢!那行得通!我添加了这个: NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; int responseCode = [httpResponse statusCode]; NSLog(@"%i", responseCode);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 1970-01-01
  • 2011-07-29
相关资源
最近更新 更多