【问题标题】:Android: Sending a byte[] array via Http POSTAndroid:通过 Http POST 发送一个 byte[] 数组
【发布时间】:2011-09-15 15:44:24
【问题描述】:

我可以对参数字符串进行 POST。我使用以下代码:

String parameters = "firstname=john&lastname=doe";
URL url = new URL("http://www.mywebsite.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestMethod("POST");

OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(parameters);
out.flush();
out.close();
connection.disconnect();

但是,我需要对二进制数据(以字节 [] 的形式)进行 POST。

不知道如何更改上面的代码来实现它。
谁能帮我解决这个问题?

【问题讨论】:

    标签: android http-post


    【解决方案1】:

    看这里 Sending POST data in Android

    但使用 ByteArrayEntity。

    byte[] content = ...
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new ByteArrayEntity(content));           
    HttpResponse response = httpClient.execute(httpPost);
    

    【讨论】:

    • 执行此行“httpPost.setEntity(new ByteArrayEntity(content));”需要很长时间(8 秒)有时在我的代码中。你知道为什么会发生这种情况吗?
    【解决方案2】:

    您可以先对数据进行 base-64 编码。看看恰当命名的Base64 类。

    【讨论】:

    • 这个想法+1。不幸的是,我不能使用 Base64,因为服务器不期望它。 (我无法对服务器进行更改,因为它迎合了许多客户端应用程序)
    【解决方案3】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 2014-03-12
    • 2017-05-17
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    相关资源
    最近更新 更多