通过Http POST请求从Android上传文件和其他数据

shi*_*tya 15 java post android http-post

这是从Android发布文件的简单方法.

String url = "http://yourserver.com/upload.php";
File file = new File("myfileuri");
try {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true); // Send in multiple parts if needed
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    //Do something with response...

} catch (Exception e) {
    e.printStackTrace();
}  
Run Code Online (Sandbox Code Playgroud)

我想要做的是POST在我的请求中添加更多变量.我怎么做?在POST请求中上传纯字符串时,我们使用URLEncodedFormEntity.

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Run Code Online (Sandbox Code Playgroud)

而在上传文件时,我们使用InputStreamEntity.

另外,我如何专门上传此文件$_FILES['myfilename']

val*_*cat 0

几个方法给你:

  • 发出 2 个发布请求:首先使用图像文件。服务器返回一个图像 ID,并在第二个请求中将您的参数附加到该 ID。

  • 或者,您可以使用 request,而不是“2 request”解决方案MultipartEntity在这里查看更多数据