HttpURLConnection, how to sending parameters via post?

拥有回忆 提交于 2019-12-02 16:09:57

问题


    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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!