2012-11-26 28 views
3

我有這樣的代碼發佈數據到我的服務器:多部分,一個部分的設置Content-Type的

// HTTP Settings 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost postRequest = new HttpPost(
        "http://myserver.com/Login"); 
      MultipartEntity reqEntity = new MultipartEntity(
        HttpMultipartMode.BROWSER_COMPATIBLE); 

      // Http Headers 
      postRequest.addHeader("Accept", "application/xml"); 
      postRequest.addHeader("Connection", "keep-alive"); 

      // Credentials 
      reqEntity.addPart("username", new StringBody(ServerData.username)); 
      reqEntity.addPart("password", new StringBody(ServerData.password)); 

      if (m_sigFile.exists()) { 
       Bitmap m_sig = BitmapFactory.decodeFile(sigFilePath 
         + "m_sig.jpg"); 
       ByteArrayOutputStream m_bao = new ByteArrayOutputStream(); 
       m_sig.compress(Bitmap.CompressFormat.JPEG, 90, m_bao); 

       byte[] m_ba = m_bao.toByteArray(); 
       String m_ba1 = Base64.encodeToString(m_ba, 0); 
       reqEntity.addPart("m_sig.jpg", new StringBody(m_ba1)); 
      } 

      postRequest.setEntity(reqEntity); 
      HttpResponse response = httpClient.execute(postRequest); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        response.getEntity().getContent(), "UTF-8")); 
      String sResponse; 
      StringBuilder s = new StringBuilder(); 

      while ((sResponse = reader.readLine()) != null) { 
       s = s.append(sResponse); 
      } 

代碼作品完美,所有的數據發送到服務器除了JPEG文件。如果我將內容類型設置爲「image/jpeg」,服務器僅接受文件,但僅限圖像。用戶名和密碼必須是純文本。這可能嗎?

回答

2

這將工作:

  ContentBody cbFile = new FileBody(new File(myPath 
        + "image_1.jpg"), 
        "image/jpeg"); 
      reqEntity.addPart("photo1"), cbFile); 

不要忘記檢查,如果你的文件存在!

1

沒有爲StringBody一個構造函數接受的內容類型:

new StringBody(titleString, "application/atom+xml", Charset.forName("UTF-8")); 
相關問題