我想在我的android应用程序中发送多部分表单,但没有使用org.apache.http.entity.mime,因此我创建了mu own方式,但它与创建请求的方式不同:
public byte[] createRequest(byte[] imagedata){
byte[] requestData = null;
ByteArrayOutputStream buf = new ByteArrayOutputStream();
OutputStreamWriter output = null;
try {
Log.i(TAG, "Creating request");
output = new OutputStreamWriter(buf, "UTF-8");
output.write("--");
output.write(boundary);
output.write("\r\n");
output.write("Content-Disposition: form-data; name=\"auth\"; filename=\"auth\"\r\n");
output.write("Content-Type: text/xml; charset=utf-8\r\n");
output.write("\r\n");
byte temp2[] = buf.toByteArray();
Log.i(TAG, "BUF SIZE: " + temp2.length);
Log.i(TAG, "BUF: " + buf.toString());
ByteArrayOutputStream authBuffer = new ByteArrayOutputStream();
OutputStreamWriter authOut = new OutputStreamWriter(authBuffer, "UTF-8");
writeAuthRequestFragment(user, pass, company_id, "RESLINK CLIENT", "2.0", null, null, null, authOut);
buf.write(authBuffer.toByteArray());
Log.i(TAG, "BUF SIZE: " + buf.size());
output.write("\r\n--" + boundary + "\r\n");
output.write("Content-Disposition: form-data; name=\""+CIMAGE+"\"; filename=\""+CIMAGE+"\"\r\n");
output.write("Content-Type: "+IMAGE_PNG+"\r\n");
output.write("\r\n");
buf.write(imagedata);
output.write("\r\n--" + boundary + "--\r\n");
requestData = buf.toByteArray();
Log.i(TAG, "WHOLE SIZE " + requestData.length);
output.flush();
} catch(IOException ex){
ex.printStackTrace();
}
finally{
if(buf!=null){
try {
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(output!=null){
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return requestData;
}
当这个方法被调用时,日志信息显示到我添加imagedata时bytearrayoutputstream的大小是0,所以看起来outputstreamwriter不写字符串,还是我错了?
有什么建议或解决办法吗?
最佳答案
如果有人会在这里寻找答案,那就是我是如何做到的:
private byte[] generatePhotoRequest(byte[] imagedata){
byte[] requestData = null;
ByteArrayOutputStream bufer = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(bufer);
try{
dataOut.writeBytes("--");
dataOut.writeBytes(BOUNDARY);
dataOut.writeBytes("\r\n");
dataOut.writeBytes("Content-Disposition: form-data; name=\"auth\"; filename=\"auth\"\r\n");
dataOut.writeBytes("Content-Type: text/xml; charset=utf-8\r\n");
dataOut.writeBytes("\r\n");
dataOut.write(generateAuth());
dataOut.writeBytes("\r\n--" + BOUNDARY + "\r\n");
dataOut.writeBytes("Content-Disposition: form-data; name=\""+CIMAGE+"\"; filename=\""+CIMAGE+"\"\r\n");
dataOut.writeBytes("Content-Type: "+IMAGE_PNG+"\r\n");
dataOut.writeBytes("\r\n");
bufer.write(imagedata);
dataOut.writeBytes("\r\n");
dataOut.writeBytes("\r\n--" + BOUNDARY + "--\r\n");
requestData = bufer.toByteArray();
} catch(IOException ex){
ex.printStackTrace();
} finally{
if(bufer!=null){
try {
bufer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return requestData;
}