2017-06-13 32 views
0

我有以下的代碼庫:對目標C中的json進行編碼並將其發送到後端的正確方法是什麼?

NSString *urlString = [NSString stringWithFormat:@"ip_address"]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setURL:[NSURL URLWithString:urlString]]; 
[request setHTTPMethod:@"POST"]; 

NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0); 
NSString *imageDataEncoded = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; 

NSMutableDictionary *jsonRequest = [[NSMutableDictionary alloc] init]; 
    [jsonRequest setObject:imageDataEncoded forKey:@"data"]; 
NSError *error; 
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:jsonRequest options:NSJSONReadingAllowFragments error:&error]; 

[request setHTTPBody:dataFromDict]; 

這是正確的方式?

在那裏我有使用Python請求庫以接收該請求,並解析JSON後端,我有一個行代碼如下:

print(base64.b64decode(request.form.get('data')) 

這將打印請求的前幾個字符如下:

ImmutableMultiDict([('{"data":"\\/9j\\/4AAQSkZJRgABAQAASA` 

正如你可以看到它真的不是一個JSON,因爲它有幾個'標記。

我該如何最好地處理收到的JSON,以及發送請求的最佳方式是什麼?

回答

1

我不認爲這是在python後端的情況。我已經將NSDictionary轉換爲NSData,就像您已經完成的操作一樣,並使用其他方法,並在NodeJS上獲得類似的請求體。 看來NSDictionary中不會轉換爲NSData的正確,因爲字典的鍵值作爲重點從NSDictionary的發送要求

帖子正文數據: NSDictionary to NSData

但是,把從的NSString的NSData提供了更多可靠的JSON數據:

NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0); 
NSString *imageDataEncoded = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; 

NSString *postString = [NSString stringWithFormat:@"data=%@", imageDataEncoded]; 
NSData *bodyData = [postString dataUsingEncoding:NSUTF8StringEncoding]; 

[request setHTTPBody:bodyData]; 

修訂

一些調查,我已經˚F後呃,我應該在請求的標題中設置Content-Type。

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

然後發送從NSDictionary轉換NSData按預期工作。

(注意:我使用ExpressJS作爲中間件中的body-parser的後端)

相關問題