2014-12-15 7 views
-1

지난 며칠간 안드로이드에 멀티 파트 양식을 게시하려고했지만 문자열 데이터와 파일을 모두 보낼 수 없습니다. 내 파일을 업로드하려면 다음 코드를 사용하고 있고 그것은 잘 작동합니다. 그러나 내 요청에 문자열 데이터를 추가 할 때 부족합니다.Android에서 파일과 함께 게시물 데이터를 보내는 방법은 무엇입니까?

요청에 profile_id=1234&text=HERE IS MY TEXT&global=0을 추가해야한다고 상상해보십시오. 어떻게해야합니까?

String fileName = photoPath; 

HttpURLConnection conn = null; 
DataOutputStream dos = null; 
String lineEnd = "\r\n"; 
String twoHyphens = "--"; 
String boundary = "*****"; 
int bytesRead, bytesAvailable, bufferSize; 
byte[] buffer; 
int maxBufferSize = 1 * 1024 * 1024; 
try { 

    // open a URL connection to the Servlet 
    FileInputStream fileInputStream = new FileInputStream(new File(photoPath)); 
    URL url = new URL(Util.URL_POST_FEED); 

    // Open a HTTP connection to the URL 
    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); 
    conn.setRequestProperty("file", fileName); 


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

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

    dos.writeBytes(lineEnd); 

    // create a buffer of maximum size 
    bytesAvailable = fileInputStream.available(); 

    bufferSize = Math.min(bytesAvailable, maxBufferSize); 
    buffer = new byte[bufferSize]; 

    // read file and write it into form... 
    bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

    while (bytesRead > 0) { 

     dos.write(buffer, 0, bufferSize); 
     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

    } 

    // send multipart form data necesssary after file data... 
    dos.writeBytes(lineEnd); 
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

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


    Log.i("uploadFile", "HTTP Response is : " 
      + serverResponseMessage + ": " + serverResponseCode); 

    if (serverResponseCode == 200) { 

     runOnUiThread(new Runnable() { 
      public void run() { 


       Toast.makeText(c, "File Upload Complete.", 
         Toast.LENGTH_SHORT).show(); 
      } 
     }); 
    } 
    InputStream stream = conn.getInputStream(); 
    InputStreamReader isReader = new InputStreamReader(stream); 

    //put output stream into a string 
    BufferedReader br = new BufferedReader(isReader); 
    Log.d("Read", br.readLine()); 
    //close the streams // 
    fileInputStream.close(); 
    dos.flush(); 
    dos.close(); 

} catch (MalformedURLException ex) { 

    ex.printStackTrace(); 

    runOnUiThread(new Runnable() { 
     public void run() { 
      Toast.makeText(c, "MalformedURLException", 
        Toast.LENGTH_SHORT).show(); 
     } 
    }); 

    Log.e("Upload file to server", "error: " + ex.getMessage(), ex); 
} catch (Exception e) { 

    e.printStackTrace(); 

    runOnUiThread(new Runnable() { 
     public void run() { 
      Toast.makeText(c, "Got Exception : see logcat ", 
        Toast.LENGTH_SHORT).show(); 
     } 
    }); 
    Log.e("Upload file to server Exception", "Exception : " 
      + e.getMessage(), e); 
} 
+1

확인하십시오. http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically –

+0

@JaiSoni 감사합니다. 완벽하게 작동했습니다. 내 대답을 들어 주시면 받아 들일 수 있을까요? –

+0

가능한 [jsp 응용 프로그램에서 다운로드를 얻기 위해 java를 사용하여 HTML 양식 데이터 제출] (http://stackoverflow.com/questions/18153691/submit-html-form-data-using-java-to-retrive-a) -download-from-a-jsp-application) – Mogsdad

답변

1

체크 this tutorial. 희망이 도움이 될 것입니다.

이 클래스는 연결을 통해 전송할 요청 본문을 수동으로 만드는 사용자 지정 MultipartUtility 클래스를 사용합니다.

관련 문제