2011-06-15 37 views
11

我能够做一个参数字符串的POST。我用下面的代码:Android:通过Http POST发送一个byte []数组

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(这是在字节[]的形式)。

不知道如何更改上面的代码来实现它。
任何人都可以帮助我吗?

回答

6

您可以先对您的数据进行base-64编码。请看一下恰当地命名为Base64的课程。

+1

+1的想法。不幸的是,我不能使用Base64,因为服务器不期望它。 (我无法更改服务器,因为它迎合了许多客户端应用程序) – OceanBlue 2011-06-16 19:43:57

8

看看这里 Sending POST data in Android

但使用ByteArrayEntity。

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

执行此行“httpPost.setEntity(new ByteArrayEntity(content))”需要很长时间(8秒);“有时在我的代码中。你知道为什么会发生这种情况吗? – 2017-03-28 18:28:51