HttpURLConnection,如何通过post发送参数?

时间:2012-01-17 19:15:35

标签: android httpurlconnection

    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);

使用上面的代码,我将图像上传到服务器,但不是如何通过post

传递参数字符串类型 谁知道呢?

2 个答案:

答案 0 :(得分:0)

表示每个参数,其中paramName = paramData:

outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes('Content-Disposition: form-data; name="paramName"' + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(paramData);

答案 1 :(得分:0)

我发现这个博客对于编写一些多部分表单数据代码很有用:
http://blog.rafaelsanches.com/2011/01/29/upload-using-multipart-post-using-httpclient-in-android/

不要忘记更改boundary变量以匹配您用于将多部分表单发送到服务器的HttpURLConnection中指定的内容。