问题
String pathToOurFile = "/sdcard/DCIM/Camera/foto.jpg";
String urlServer = "http://server/upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
.
.
.
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
with the code above, i upload a image to server, but not how to pass parameters string type via post
anyone knows?
回答1:
for each parameter, where paramName=paramData:
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes('Content-Disposition: form-data; name="paramName"' + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(paramData);
回答2:
I found this blog useful for writing some multipart form data code:
http://blog.rafaelsanches.com/2011/01/29/upload-using-multipart-post-using-httpclient-in-android/
Don't forget to change the boundary
variable to match what you specify in the HttpURLConnection
that you're using to send the multipart form to the server.
来源:https://stackoverflow.com/questions/8900337/httpurlconnection-how-to-sending-parameters-via-post