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

时间:2013-04-12 09:50:36

标签: java android post 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();
}  

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

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

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

4 个答案:

答案 0 :(得分:1)

由于您希望从应用中上传文件,以下是一个很好的教程:

Uploading files to HTTP server using POST on Android.

如果你想上传字符串,我想你已经知道了解决方案:)

答案 1 :(得分:1)

最有效的方法是使用android-async-http

您可以使用此代码上传文件:

 

    File myFile = new File("/path/to/file.png");
    RequestParams params = new RequestParams();
    try {
        params.put("profile_picture", myFile);
    } catch(FileNotFoundException e) {}

答案 2 :(得分:1)

找了loopj一整天后。您可以按照以下代码示例:

//context: Activity context, Property: Custom class, replace with your pojo
public void postProperty(Context context,Property property){
        // Creates a Async client. 
        AsyncHttpClient client = new AsyncHttpClient();
         //New File
        File files = new File(property.getImageUrl());
        RequestParams params = new RequestParams();
        try {
            //"photos" is Name of the field to identify file on server
            params.put("photos", files);
        } catch (FileNotFoundException e) {
            //TODO: Handle error
            e.printStackTrace();
        }
        //TODO: Reaming body with id "property". prepareJson converts property class to Json string. Replace this with with your own method 
        params.put("property",prepareJson(property));
        client.post(context, baseURL+"upload", params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                System.out.print("Failed..");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                System.out.print("Success..");
            }
        });

    }

答案 3 :(得分:0)

有几种方法:

  • 发布2个帖子请求:首先使用图片文件。服务器返回一个图像ID,第二个请求你附加到这个id你的参数。

  • 或者,您可以使用MultipartEntity请求代替“2请求”解决方案。 Look here for more datails