2012-01-17 191 views
0
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); 

與上面的代碼,我上傳到服務器中的圖像,而不是如何通過郵寄HttpURLConnection,如何通過post發送參數?

有誰知道傳遞參數字符串類型?

+0

檢查此http://stackoverflow.com/questions/2253061/secure-http-post-in-android和此http://moazzam-khan.com/blog/?tag=android-http-post鏈接考慮使用HttpGet和HttpPost類 – 2012-01-17 19:45:09

+0

試試我的方式: [Android - HttpURLConnection參數從Map 通過POST方法](http://stackoverflow.com/questions/33448973/android-httpurlconnection-parameters-from-mapstring- object-via-post-method) – 2015-10-31 07:01:15

回答

0

每個參數,其中PARAMNAME = paramData:

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

我用 String param =「valor」; outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes(「Content-Disposition:form-data; name = \」param \「」+ lineEnd); outputStream.writeBytes(lineEnd); outputStream.writeBytes(lineEnd); outputStream.writeBytes(param); outputStream.writeBytes(param); 並不起作用,'知道這是錯的? – 2012-01-17 20:12:59

+0

當您刪除文件提交時是否有效?是否需要在param數據之後提交文件? – elijah 2012-01-17 20:22:24

+0

完成!將參數字符串類型放在文件類型參數之後 – 2012-01-17 21:47:48