簡體   English   中英

簡單的iOS POST HTTP請求

[英]Simple iOS POST http request

我正在尋找從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數據庫,我知道它正在工作並且正在正確發布。 但是,如何查看其返回的狀態代碼?

我正在對所有HTTP通信使用AFNetworking庫

發布請求的代碼如下所示:

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
}];

如果您對使用第三方庫不感興趣(盡管它通常可以簡化您的工作),則可以使用本機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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM