这个问题似乎很愚蠢,但我不想犯错误。 正如标题中所解释的,我想使用post方法将多个字段发送到WS。简单来说,标题(字符串)和图像。 到目前为止,我已经成功地发送了图像(经过很多麻烦之后)。
这是android代码:
String urlServer = GlobalSession.IP + "insert_reportByte";
URL url = new URL(urlServer);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type","multipart/form-data");
DataOutputStream outputStream = new DataOutputStream(
connection.getOutputStream());
outputStream.write(outputByteArray, 0, outputByteArray.length);
Log.d("Report", " Amount of data sent for the picture: " + outputByteArray.length);
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
outputStream.flush();
outputStream.close();
即成功发送图片(outputByteArray)以下WS:
public void insert_reportByte(Stream input)
{
MyEntities entities = new MyEntities();
byte[] image = new byte[30*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(image, 0, image.Length)) > 0)
{
ms.Write(image, 0, read);
}
}
String base64stringimage = System.Convert.ToBase64String(image,0,image.Length);
entities.insert_report("name hard coded", base64stringimage);
}
所以,我想从那个说法转换为public void insert_reportByte(String name, Stream input)
。怎么办?或者我是否必须在流中发送所有内容然后逐个恢复传输的参数?
感谢您的提示!
答案 0 :(得分:1)
看起来您的问题是处理Multipart data请求。
对于Android客户端,你可以查看this answer,有一个MultipartEntity
,它是由多个正文部分组成的多部分/表格编码的HTTP实体。您的请求工具如下所示:
HttpPost httppost = new HttpPost(urlServer);
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("name", new StringBody("your input name here"));
multipartEntity.addPart("Image", new FileBody(new File(imagePath)));
httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost);
从服务器端,您只需要一个流参数。但是您需要以不同的方式解析此流。Here是一个使用form parser library的示例。因此,您的方法应如下所示:
public void insert_reportByte(Stream stream)
{
HttpMultipartParser parser = new HttpMultipartParser(data, "Image");
if (parser.Success)
{
// get the name from android client
string name = HttpUtility.UrlDecode(parser.Parameters["name"]);
// Save the file somewhere
File.WriteAllBytes(your_server_file_path, parser.FileContents);
}
}
希望这可以提供帮助。
答案 1 :(得分:0)
你需要像你一样在你的请求中添加NameValue对!
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair(name, "myName"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
我希望它会有所帮助!见this回答!