带参数和文件的Android httpPost [英] Android httpPost with parameters and file

查看:30
本文介绍了带参数和文件的Android httpPost的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要上传一些数据到 PHP 服务器.我可以使用参数进行发布:

I need to upload some data to PHP server. I can do post with parameters:

String url = "http://yourserver";

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
nameValuePairs.add(new BasicNameValuePair("user", "username"));
nameValuePairs.add(new BasicNameValuePair("password", "password"));
try {
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    httpClient.execute(httpPost);
}

我也可以上传文件:

String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory(),
        "yourfile");
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...
}

但是我怎样才能把它放在一起呢?我需要在一篇文章中上传图像和参数.谢谢

But how can I put it together? I need to upload an image and parameters in one post. Thanks

推荐答案

您必须使用多部分 http 帖子,就像在 HTML 表单中一样.这可以通过额外的库来完成.有关完整示例,请参阅 使用 Http Post 发送图像 帖子.

You must use a multipart http post, like in HTML forms. This can be done with an extra library. See the post Sending images using Http Post for a complete example.

这篇关于带参数和文件的Android httpPost的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆