I have uploading photos using an android script that loads fine, if I use $ _GET to read some data, I want to use all $ _POST. The problem is that I need to add data so that the published request includes the main pairs of name values along with the file upload. I can make this work if I use the $ _GET server and just add extra data to the url string, but I want to use post. Is there a way to encode other data after downloading a file that the server can read using $ _POST. Heres function, pay attention to the URL bar where I try to get the api_key, session_key and method to send in the POST request.
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);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
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);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1028;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
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);
dos.flush();
InputStream is = conn.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String s = b.toString();
dos.close();
}
EDIT I think for each parameter added
The following is required: dos.writeBytes("--" + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data;name=api_key=" + lineEnd + lineEnd + API_KEY);
dos.writeBytes(lineEnd);
dos.writeBytes("--" + boundary + "--" + lineEnd);
Brian source
share