2011-05-25 94 views
0

嗨,Android中的HttpURLConnection參數傳遞問題?

我使用下面的代碼部分上傳文件到服務器,連同這個文件我需要發送一些關於這個文件的參數,我不知道如何發送參數以及文件,但是我可以上傳文件。

   FileInputStream fileInputStream = new FileInputStream(sourceFile); 
     URL url = new URL(upLoadServerUri); 
     conn = (HttpURLConnection) url.openConnection(); 

     conn.setDoInput(true); // Allow Inputs 
     conn.setDoOutput(true); // Allow Outputs 
     conn.setUseCaches(false); // Don't use a Cached Copy 
     conn.setRequestMethod("POST"); 

     conn.setRequestProperty("Connection", "Keep-Alive"); 
     conn.setRequestProperty("ENCTYPE", "multipart/form-data"); 

     conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 


     dos = new DataOutputStream(conn.getOutputStream()); 

     dos.writeBytes(twoHyphens + boundary + lineEnd); 
     dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""+ fileName + "\"" + lineEnd); 
     dos.writeBytes(lineEnd); 

     bytesAvailable = fileInputStream.available(); 



     bufferSize=(int)sourceFile.length(); 


     buffer = new byte[1024]; 
     int len; 
     int state=0; 
     while((len=fileInputStream.read(buffer))>0){ 
      state=state+len; 
      dos.write(buffer); 
      publishProgress(state); 
     } 

     dos.writeBytes(lineEnd); 
     dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

     // Responses from the server (code and message) 
     serverResponseCode = conn.getResponseCode(); 
     String serverResponseMessage = conn.getResponseMessage(); 


     // close streams 
     Log.i("Upload file to server", fileName + " File is written"); 
     fileInputStream.close(); 
     dos.flush(); 
     dos.close(); 
     } catch (MalformedURLException ex) { 
     ex.printStackTrace(); 
     Log.e("Upload file to server", "error: " + ex.getMessage(), ex); 
     } catch (Exception e) { 
     e.printStackTrace(); 
     } 
    //this block will give the response of upload link 
     try { 
     BufferedReader rd = new BufferedReader(new InputStreamReader(conn 
     .getInputStream())); 

     while ((line = rd.readLine()) != null) { 
     Log.i("Huzza", "RES Message: " + line); 


     } 
     rd.close(); 
     } catch (IOException ioex) { 
     Log.e("Huzza", "error: " + ioex.getMessage(), ioex); 

     } 

如果有人知道問題幫助我。

回答

0

使用http客戶端與多部分實體。你將需要額外的庫。

這裏是一個很好的一篇關於如何做到這一點:

MultipartEntity