1

我正在将其他人的 iOS 应用程序转换为 android,我遇到了无法制作他们正在创建的这个多部分实体的正面或反面的问题。

NSMutableData *body = [NSMutableData data];

    // file
    NSData *imageData = UIImageJPEGRepresentation(image, 90);

    NSString *boundary = [NSString stringWithFormat:@"---------------------------14737809831466499882746641449"];
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: attachment; name=\"imagefile\"; filename=\"user_%@.jpg\"\r\n",userID] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];


    // UserID
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userid\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:userID] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

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

我认为看起来像这样

---------------------------14737809831466499882746641449
Content-Disposition: attachment; 
name=\"imagefile\"; filename=\"user_" + userID +".jpg\"
Content-Type: application/octet-stream
imagedata

---------------------------14737809831466499882746641449
Content-Disposition: form-data; 
name=\"userid\"

userID

---------------------------14737809831466499882746641449--

现在我正在尝试使用 MultiPartEntity 在 java 中重建它

ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();

HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(url);

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8"));

并坚持为文本计算等效的多部分。

任何帮助,将不胜感激。

4

1 回答 1

1

就是这个

     entity.addPart("imagefile", new ByteArrayBody(imageBytes, "image/jpeg", "user_" + userId + ".jpg"));
     entity.addPart("userid", new StringBody(userId));

如此简单易行,只需尝试 30 种不同的方法即可。

于 2013-05-28T21:08:04.027 回答