0

我目前正在开发一个 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());
}
4

1 回答 1

1

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

看看Java ME 中的 HTTP Post 多部分文件上传。您可以使用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();
于 2013-11-08T12:05:03.653 回答