使用Android到Objective - C的多部分表单数据(NSDictionary和图像)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Android到Objective - C的多部分表单数据(NSDictionary和图像)相关的知识,希望对你有一定的参考价值。

下午好!我正在尝试提出类似于此的请求:

public boolean ChangeAvatar(final Bitmap avatarBitmap, final IChangeAvatar handler)
{
    String url = baseUrl + Language.getInstance().getLanguage() + "/my_url";
    final JSONObject params = new JSONObject();
    try {
        JSONObject auth = new JSONObject();
        auth.put("uid",Long.toString(UserData.getInstance().getUserId()));
        auth.put("token", UserData.getInstance().getUserToken());
        params.put("auth",auth);
        params.put("act","avatar_change");
    }
    catch (Exception e)
    {
        Log.e("network",e.getMessage());
        return false;
    }
    VolleyMultipartRequest myRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
        @Override
        public void onResponse(NetworkResponse response) {
            try {
                String responseStr = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
                handler.ChangeSuccess("");
                //JSONObject resp = new JSONObject(responseStr);
                Log.d("network", responseStr);
            }
            catch (Exception e)
            {
                handler.ChangeFailed("error","Error");
                Log.d("network", e.getMessage());
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if(error.getMessage()!= null)
                handler.ChangeFailed("error",error.getMessage());
            else
            {
                try {
                    String responseStr = new String(error.networkResponse.data, HttpHeaderParser.parseCharset(error.networkResponse.headers));
                    handler.ChangeFailed("error","errorMessage");
                }
                catch (Exception e)
                {

                    handler.ChangeFailed("error","errorMessage");
                }

            }

        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String,String> paramsMap = new HashMap<>();
            paramsMap.put("json",params.toString());
            return paramsMap;
        }

        @Override
        protected Map<String, DataPart> getByteData() {
            HashMap<String,DataPart> result = new HashMap<>();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            avatarBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            final byte[] byteArrayImage = baos.toByteArray();
            result.put("userfile",new DataPart("avatar.jpg",byteArrayImage,"image/jpeg"));
            return result;
        }
    };
    myRequest.setRetryPolicy(new DefaultRetryPolicy(5000,0,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    RequestManager.getInstance(context).addToRequestQueue(myRequest);
    return true;
}

但我总是得到一个错误。在我看来,我的问题是我的图像的错误密钥传输。以下是目前的发展情况:

- (IBAction)saveAction:(UIButton *)sender
{
    NSMutableDictionary *auth = [NSMutableDictionary dictionary];
    [auth setValue:[UserDefaultsHandler getUserDefaultsValueByKey:@"myId"] forKey:@"uid"];
    [auth setValue:[UserDefaultsHandler getUserDefaultsValueByKey:@"token"] forKey:@"token"];

    NSMutableDictionary *userDataDictionary = [NSMutableDictionary dictionary];
    [userDataDictionary setValue:auth forKey:@"auth"];
    [userDataDictionary setValue:@"avatar_change" forKey:@"act"];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:[NSURL URLWithString:@"myUrl"]];

    [request setHTTPMethod:@"POST"];

    NSMutableData *body = [NSMutableData data];

    NSString *boundary = @"---------------------------14737809831466499882746641449";

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];

    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSData* imageData = UIImageJPEGRepresentation(self.imageView.image, 1.0f);

    [body appendData:[[NSString stringWithFormat:@"--%@
", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[@"Content-Disposition: form-data; name="userfile"; fileName="avatar.jpg"
" dataUsingEncoding:NSUTF8StringEncoding]];


    [body appendData:[@"Content-Type: image/jpeg

" dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:imageData];

    [body appendData:[@"
" dataUsingEncoding:NSUTF8StringEncoding]];

    //  parameter all_data
    [body appendData:[[NSString stringWithFormat:@"--%@
", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name="all_data"

"] dataUsingEncoding:NSUTF8StringEncoding]];

    NSString *jsonStr = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:userDataDictionary options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];

    [body appendData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[@"
" dataUsingEncoding:NSUTF8StringEncoding]];

    // close form
    [body appendData:[[NSString stringWithFormat:@"--%@--
", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    // setting the body of the post to the request
    [request setHTTPBody:body];

    NSError *error=nil;
    NSHTTPURLResponse *response=nil;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
答案

看看这个,也许有帮助:

    NSString *URLPath;//URL
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLPath] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:questionDict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];

    NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    /*
     ....
     ....
     */
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData];

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    }];
    [task resume];

或者(比这更容易)

AFNetworkingios的网络框架)

以上是关于使用Android到Objective - C的多部分表单数据(NSDictionary和图像)的主要内容,如果未能解决你的问题,请参考以下文章

Objective-C:Swift Package 函数中的多参数方法语法

如何有效地迭代 NSSet (Objective-C) - Core Data 中的多对多关系表示?

swift 3中的多选下拉菜单

使用支持 Objective-C 的 gcc 错误编译 Android NDK

Kotlin 与 Objective-C 框架的多平台/本机互操作性

Swift 中的多变量赋值