【问题标题】:POST request with file (image) and text with HttpURLConnection带有文件(图像)和带有 HttpURLConnection 的文本的 POST 请求
【发布时间】:2016-12-06 00:31:15
【问题描述】:

我有以下在 Bash 中工作的 cURL

$ curl -F "image=@/Users/my-name/Downloads/STARinside.jpg_256" -F "assetNumber=OS014005" -F "name=George" -F "make=Hamilton" -F "model=STAR" "http://exampleUrl.compute.amazonaws.com/Asmt3/updateInstrImage.php"

但我似乎无法在 Android Studio 中完成这项工作。这是我尝试过的一些代码,但我似乎无法开始工作。我可以自己获取所有参数的 POST(包括 image=@filename),但似乎服务器(这是我编写的 php)在$_FILES['image'] 中没有收到任何东西,就像它从 bash 中一样。或者我可以通过 bufferedOutputStream 发送实际文件,但它不会在 $_POST 数组中捕获任何有意义的内容。

这段代码在AsyncTask的扩展中,FTR:

HttpURLConnection conn = (HttpURLConnection) this.updateInstr.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
//conn.setRequestProperty("Content-Type", "image/jpeg");
conn.setDoInput(true);
params.append("assetNumber=");
params.append(this.asset);
params.append("&name=");
params.append(InstrList.get(this.asset));
params.append("&make=");
params.append(InstrMakes.get(this.asset));
params.append("&model=");
params.append(InstrModels.get(this.asset));
params.append("&image=@");
params.append(image.getAbsoluteFile());
/*
    conn.addRequestProperty("assetNumber", this.asset);
    conn.addRequestProperty("name", InstrList.get(asset));
    conn.addRequestProperty("make", InstrMakes.get(asset));
    conn.addRequestProperty("model", InstrModels.get(asset));
*/
conn.setChunkedStreamingMode(bt.length);
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
byte[] b = params.toString().getBytes(StandardCharsets.US_ASCII);
out.write(b);
out.flush();
out.write(bt);
out.flush();
out.close();

//fully open connection with conn.getInputStream
InputStream in = new BufferedInputStream(conn.getInputStream());
in.read(bytes);
in.close();
response = new String(bytes, "utf-8");
Log.d("response: ", response);

另外,您可以看到,我尝试了与conn.addRequestProperty 不同的方法。在那个实现中,我尝试在 bt 之后写 b(在 FILE 之后发布)。

我绝对会感谢您的帮助。看来我应该能够在 Android Studio 中复制这个 cURL 调用,但我就是不太明白。我已经在服务器上的 php 中添加了一些回显,所以我知道我正确地组装了参数($_POST 数组基于print_r($_POST) 调用是正确的),但是$_FILES 数组在 android 中是空的工作室(但从 bash-curl 来看是正确的)

请注意,我确实找到了this other question,这非常有用并且几乎足够了,但似乎为 Java 讨论的 ByteArrayBody 类在 Android Studio 中不存在

【问题讨论】:

    标签: php android android-studio curl http-post


    【解决方案1】:

    事实证明这非常复杂,我需要分散在 SO 和其他地方的几个不同的资源来(最终)让它工作。

    所以,我在我的免费亚马逊 EC2 实例上发布了一个非常详细的示例。如果有人想获取来源并将其发布到其他地方,我很乐意为您这样做,只要您说明原作者。现在:

    http://ec2-54-213-243-1.us-west-2.compute.amazonaws.com/How-to/index.html

    要点是您需要扩展 AsyncTask,但您还需要逐个字符地构建 Http 请求来描述什么是文件(字节流)与“普通”数据字段。

    涉及最多的部分是: 哪个调用:

    【讨论】:

      猜你喜欢
      • 2016-12-02
      • 2020-03-22
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 2021-05-21
      相关资源
      最近更新 更多