gpt4 book ai didi

java - 使用 HTTP Post 多部分上传文件 - 4Sharing API J2ME

转载 作者:行者123 更新时间:2023-12-01 13:52:41 25 4
gpt4 key购买 nike

我目前正在开发一个 J2ME 应用程序。我在上传文件时遇到问题。我似乎不知道我的代码的哪一部分是错误的。这是我的代码:

public void UploadImage(long newFileId, String url, String bytes){
HttpConnection conn = null;
OutputStream os = null;
InputStream s = null;
StringBuffer responseString = new StringBuffer();


try
{

System.out.println(System.getProperty("HTTPClient.dontChunkRequests"));
conn.setRequestMethod(HttpConnection.POST);
conn = (HttpConnection)Connector.open(url);
conn.setRequestProperty("resumableFileId", ""+newFileId);
conn.setRequestProperty("resumableFirstByte", ""+0);
conn.setRequestProperty("FilePart", bytes);


// Read

s = conn.openInputStream();
int ch, i = 0, maxSize = 16384;
while(((ch = s.read())!= -1 ) & (i++ < maxSize))
{
responseString.append((char) ch);
}

conn.close();
System.out.println(responseString.toString());
String res = uploadFinishFile(newFileId, bytes);
if(res.length()>0)
System.out.println("File uploaded.");
else
System.out.println("Upload failed: "+res);
}
catch (Exception e)
{
System.out.println(e.toString());
}


}

这是我试图转换为 j2me 的 java 代码:

try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntity me = new MultipartEntity();
StringBody rfid = new StringBody("" + newFileId);
StringBody rfb = new StringBody("" + 0);
InputStreamBody isb = new InputStreamBody(new BufferedInputStream(new FileInputStream(f)), "FilePart");
me.addPart("resumableFileId", rfid);
me.addPart("resumableFirstByte", rfb);
me.addPart("FilePart", isb);

post.setEntity(me);
HttpResponse resp = client.execute(post);
HttpEntity resEnt = resp.getEntity();

String res = da.uploadFinishFile(login, password, newFileId, DigestUtils.md5Hex(new FileInputStream(f)));
if(res.isEmpty())
System.out.println("File uploaded.");
else
System.out.println("Upload failed: "+res);
} catch (Exception ex) {
System.out.println("Upload failed: "+ex.getMessage());
}

最佳答案

您正在上传将参数作为 HTTP header 传递的文件,而不是使用分段文件上传在 HTTP 消息正文中发送图像,这与您要转换的代码兼容。

看看HTTP Post multipart file upload in Java ME 。您可以使用 HttpMultipartRequest 类并将代码更改为:

Hashtable params = new Hashtable();
params.put("resumableFileId", "" + newFileId);
params.put("resumableFirstByte", "" + 0);

HttpMultipartRequest req = new HttpMultipartRequest(
url,
params,
"FilePart", "original_filename.png", "image/png", isb.getBytes()
);

byte[] response = req.send();

关于java - 使用 HTTP Post 多部分上传文件 - 4Sharing API J2ME,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19851020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com