我正在尝试使用 Multipart/form-data 将图像上传到服务器,我必须在同一个调用中发送一些文本和图像。当我只发送原始数据时,它工作正常,但是当我添加“图像上传部分”时它不起作用。下面是我的代码。
public String upLoadPostMethod(List<NameValuePair> params, boolean isUploadingPhoto) {
NameValuePair nvp = params.get(1);
String args = nvp.getValue();
System.out.println(args);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "********";
HttpsURLConnection conn;
String response = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String mimeType = "image/jpeg";
try {
URL url = new URL(webServiceUrl);
conn = (HttpsURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
//conn.setChunkedStreamingMode(0);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cookie",
appStatus.getSharedStringValue(appStatus.AUTH_KEY));
System.out.println(appStatus
.getSharedStringValue(appStatus.AUTH_KEY));
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
DataOutputStream dos;
dos = new DataOutputStream(conn.getOutputStream());
// Send parameter #1
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"cmd\""
+ lineEnd + lineEnd);
dos.writeBytes("tsql" + lineEnd);
// Send parameter #2
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"args\""
+ lineEnd + lineEnd);
dos.writeBytes(args + lineEnd);
System.out.println("args======" + args);
if(isUploadingPhoto){
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";"
+"filename=\" 20130125_155208.jpg\"" +"Content-Type: "+mimeType +lineEnd+lineEnd);
FileInputStream fileInputStream = new FileInputStream(Environment.getExternalStorageDirectory().getPath()
+"/20130125_155208.jpg");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
}else {
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
}
dos.flush();
dos.close();
Scanner inStream = new Scanner(conn.getInputStream());
while (inStream.hasNextLine())
response += (inStream.nextLine());
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
我在这里做错了什么吗?