HttpURLConnection类,如何通过邮递方式寄往参数?参数、寄往、方式、HttpURLConnection

2023-09-04 05:24:50 作者:怪咖萌宠

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

与code以上,我上传图像到服务器上,而不是如何通过邮寄传递参数字符串类型

with the code above, i upload a image to server, but not how to pass parameters string type via post

有谁知道?

推荐答案

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

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/

不要忘记更改边界变量来匹配您在的HttpURLConnection 你是指定哪些使用以多部分形式发送到服务器。

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.