使用HTTPClient使用RestKit 0.20上传文件(File uploads with RestKit 0.20 using HTTPClient)
我目前正在使用以下代码发布到我的服务器:
[[[RKObjectManager sharedManager] HTTPClient] postPath:[NSString stringWithFormat:@"%@%@", baseURL, @"/api/v2/track-it/rack/individual"] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { // handle success if([[responseObject[@"result"] lowercaseString] isEqualToString:@"success"]){ // Entry was added UIViewController *otherVC = [[UIStoryboard storyboardWithName:@"App" bundle:nil] instantiateViewControllerWithIdentifier:@"Dashboard"]; [self presentViewController:otherVC animated:YES completion:nil]; [self alertWithTitle:@"Track It Entry" message:@"The entry was uploaded successfully"]; } else { // Couldn't add entry [self alertWithTitle:@"Track It Entry" message:@"An error occured. Saving entry to upload later."]; } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // response code is in operation.response.statusCode NSLog(@"ERROR"); }];
params
是值的NSDictionary
。如何上传文件?
我在任何没有使用托管对象的地方都找不到任何示例。I am currently using the following code to post to my server:
[[[RKObjectManager sharedManager] HTTPClient] postPath:[NSString stringWithFormat:@"%@%@", baseURL, @"/api/v2/track-it/rack/individual"] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { // handle success if([[responseObject[@"result"] lowercaseString] isEqualToString:@"success"]){ // Entry was added UIViewController *otherVC = [[UIStoryboard storyboardWithName:@"App" bundle:nil] instantiateViewControllerWithIdentifier:@"Dashboard"]; [self presentViewController:otherVC animated:YES completion:nil]; [self alertWithTitle:@"Track It Entry" message:@"The entry was uploaded successfully"]; } else { // Couldn't add entry [self alertWithTitle:@"Track It Entry" message:@"An error occured. Saving entry to upload later."]; } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // response code is in operation.response.statusCode NSLog(@"ERROR"); }];
params
is anNSDictionary
of values.How can I upload files with this?
I can't find any examples anywhere that aren't using a Managed Object.
原文:https://stackoverflow.com/questions/31865535
最满意答案
您需要自定义模型联编程序才能正常工作。 这是您可以开始使用的简化版本:
public class CsvIntModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var key = bindingContext.ModelName; var valueProviderResult = bindingContext.ValueProvider.GetValue(key); if (valueProviderResult == null) { return false; } var attemptedValue = valueProviderResult.AttemptedValue; if (attemptedValue != null) { var list = attemptedValue.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries). Select(v => int.Parse(v.Trim())).ToList(); bindingContext.Model = list; } else { bindingContext.Model = new List<int>(); } return true; } }
并以这种方式使用它(从路由中删除
{ids}
):[HttpGet] [Route("api/NewHotelData")] public HttpResponseMessage Get([ModelBinder(typeof(CsvIntModelBinder))] List<int> ids)
如果您想保留
{ids}
的路线,您应该将客户端请求更改为:api/NewHotelData/1,2,3,4
另一个选项( 没有自定义模型绑定)正在将获取请求更改为:
?ids=1&ids=2&ids=3
You'll need custom model binder to get this working. Here's simplified version you can start work with:
public class CsvIntModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var key = bindingContext.ModelName; var valueProviderResult = bindingContext.ValueProvider.GetValue(key); if (valueProviderResult == null) { return false; } var attemptedValue = valueProviderResult.AttemptedValue; if (attemptedValue != null) { var list = attemptedValue.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries). Select(v => int.Parse(v.Trim())).ToList(); bindingContext.Model = list; } else { bindingContext.Model = new List<int>(); } return true; } }
And use it this way (remove
{ids}
from route):[HttpGet] [Route("api/NewHotelData")] public HttpResponseMessage Get([ModelBinder(typeof(CsvIntModelBinder))] List<int> ids)
If you want to keep
{ids}
in route, you should change client request to:api/NewHotelData/1,2,3,4
Another option (without custom model binder) is changing get request to:
?ids=1&ids=2&ids=3
相关问答
更多-
您可以使用库Apache HTTP组件 doGet()简短示例(我没有编译它): import org.apache.http.*; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http. ...
-
作为快速修复,将Play更改为PlayAPI.Models.Product上的Int64。 public Int64 Stock { get; set; } 我的理解是,用于修补现有对象的Delta对象不使用JSON.net进行转换,并在分析JSON时静默抛出无效的强制转换异常,然后与数据库中的现有对象进行比较。 您可以在此处阅读有关该错误的更多信息: http : //aspnetwebstack.codeplex.com/workitem/777 As a quick fix, Change the ...
-
从客户端调用Web API(Calling Web API from client)[2022-04-11]
好。 我找到了解决方案。 当前的API服务代码保持不变。 客户端代码将在字符串中包含请求参数,并将其作为参数传递给服务。 完成。 自动模型绑定将触发 OK. I found a solution to this. Current API Service code remains same. client code will have request params in a string and pass this as a param to the Service. Done. Auto model bin ... -
发送多个Web请求(Send multiple Web requests)[2021-09-14]
只是不要“屈服”“获取”返回的未来。 然后你的协同将立即继续循环,并且当fetch在后台完成时执行回调。 此外,永远不要在Tornado应用程序中调用“sleep”: http://www.tornadoweb.org/en/stable/faq.html#why-isn-t-this-example-with-time-sleep-running-in-parallel 如果这样做,所有处理都会停止,并且“fetch”将一直挂起,直到睡眠完成。 代替: yield gen.sleep(delay) Si ... -
你可以使用这个: 在Json中请求正文 [{id:1, nombre:"kres"}, {id:2, nombre:"cruz"}] Api Rest .net C# public string myFunction(IEnumerable
myObj) { //... return "response"; } You can use this : Request body in Json [{id:1, nombre:"kres"}, {id:2, n ... -
使用Newtonsoft.Json库来序列化您的凭证对象。 你的Consume功能就是这样 private static string Consume(string endpoint, string user, string password) { var client = new HttpClient(); client.BaseAddress = new Uri(endpoint); client.DefaultRequestHeaders.Accept.Clear(); ...
-
您需要自定义模型联编程序才能正常工作。 这是您可以开始使用的简化版本: public class CsvIntModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var key = bindingContext.ModelName; var valueProviderRe ...
-
PutAsync不向web api发送请求,但fiddler工作正常(PutAsync doesn't send request to web api, but fiddler works fine)[2023-02-25]
HttpClient.PutAsync是一个异步API,它返回一个Task,它表示将来需要await 。 你将HttpClient包装在using语句中,这意味着在你触发异步PUT之后,你正在处理客户端,这会导致请求和处理对象的竞争条件,这可能是你'的原因。没有看到请求火了。 你有两个选择。 使方法成为async Task并在其中await : public async Task UpdateWerknemerCompetentieDetailAsync( ... -
你不需要做任何事情,这将开箱即用。 如果您发布您提供的确切对象: { "ID" : 3 , "SelectedChoiceIDs" : [ 3,4,5,6 ] } 使用Content-Type: application/json ,默认的模型绑定器将自动拾取它。 public class PostData { public int ID { get; set; } public int[] SelectedChoiceIDs { get; set; } } public void ...
-
如何通过Angular向ASP.net web API发送帖子请求(How to send post request through Angular to ASP.net web API)[2022-06-26]
您正在使用的params选项将项添加到查询字符串,对于您可能希望使用数据选项的帖子,请尝试将代码更改为: $scope.UpdateTrans=function(){ alert("21312"); $http({method:"post", url:'http://localhost:18678/api/Transaction', data:$scope.AddTrn } ...