我有一个Android照片上传脚本,如果使用$_GET读取一些数据,则可以成功上传,但我想要使用全部的$_POST。问题是我需要将数据附加到已发布的请求中,以包括基本的名称值对和文件上传。如果让服务器使用$_GET并在url字符串中添加额外的数据,我可以使其工作,但我想要使用post。是否有一种方法可以在文件上传中编码其他POST数据,以便服务器可以使用$_POST读取?以下是该功能,请注意URL字符串,我正在尝试获取变量api_key、session_key和method以在POST请求中发送。
public void uploadPhoto(FileInputStream fileInputStream, String sessionKey) throws IOException, ClientProtocolException {
URL connectURL = new URL(API_URL +"?api_key=" +API_KEY+ "&session_key=" + sessionKey + "&method=" + ApiMethods.UPLOAD_PHOTO); //server ignores this data
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""+ "file.png" + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1028;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int 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);
*/
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
// Log.d(TAG, " dos5: " + dos.toString());
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String s = b.toString();
dos.close();
}
编辑 我认为每个添加的参数都需要类似以下的内容
dos.writeBytes("--" + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data;name=api_key=" + lineEnd + lineEnd + API_KEY);
dos.writeBytes(lineEnd);
dos.writeBytes("--" + boundary + "--" + lineEnd);