2012-11-09 70 views
3

我正在實施一個與發送文件到服務器相關的應用程序。如何在android中使用http post方法發送文件?

我想通過使用http post方法發送文件到服務器。

我通過使用下面的代碼從SD卡獲取文件。

File root = Environment.getExternalStorageDirectory(); 
String pathToOurFile = root+"111"; 

我的代碼看起來像休閒。

StringBuilder response = new StringBuilder(); 
try { 
    HttpPost post = new HttpPost(); 
    post.setURI(uri); 
    List params = new ArrayList(); 
    params.add(new BasicNameValuePair("paramName", "paramValue")); 
    post.setEntity(new UrlEncodedFormEntity(params)); 
    DefaultHttpClient httpClient = new DefaultHttpClient(); 
    HttpResponse httpResponse = httpClient.execute(post); 
    if (httpResponse.getStatusLine().getStatusCode() == 200) { 
    Log.d(APP_TAG, "HTTP POST succeeded"); 
    HttpEntity messageEntity = httpResponse.getEntity(); 
    InputStream is = messageEntity.getContent(); 
    BufferedReader br = new BufferedReader(new InputStreamReader(
    openFileInput(pathToOurFile))); 
    String line; 

    while ((line = br.readLine()) != null) { 
    Log.v("info",",,,"+line); 
    response.append(line); 
    } 
    } else { 
    Log.e(APP_TAG, "HTTP POST status code is not 200"); 
    } 
} catch (Exception e) { 
    Log.e(APP_TAG, e.getMessage()); 
} 

但它是不正確的。

如果知道解決方案,請幫我

在此先感謝。

回答

3

這應該工作,我還沒有測試代碼。

import org.apache.http.HttpEntity; 
    import org.apache.http.HttpResponse; 
    import org.apache.http.client.HttpClient; 
    import org.apache.http.client.methods.HttpPost; 
    import org.apache.http.entity.mime.MultipartEntity; 
    import org.apache.http.entity.mime.content.FileBody; 
    import org.apache.http.entity.mime.content.StringBody; 
    import org.apache.http.impl.client.DefaultHttpClient; 

    ... 

     public static void uploadFile() throws Exception { 
      HttpClient httpclient = new DefaultHttpClient(); 
      try { 
       HttpPost httppost = new HttpPost(uri); 
       String pathToOurFile = root+"111"; 

       File f = new File(pathToOurFile); 
       FileBody bin = new FileBody(f); 


       MultipartEntity reqEntity = new MultipartEntity(); 
       reqEntity.addPart("file", bin); 
       reqEntity.addPart("paramName", paramValue); 

       httppost.setEntity(reqEntity); 

       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity resEntity = response.getEntity(); 

       String postResponse = response.getStatusLine(); 
     } 

    } 
+0

我使用上面的代碼。但FileBody和MultipartEntity想創建一個class.haveü使用任何jar文件here.Thanq爲u'r回覆 – kiran

+0

其他人誰到這裏,需要的庫:HTTP ://hc.apache.org/downloads.cgi下載帶有缺失庫的httpclient,你可以將該庫中的httpmime jar放到你的項目中 –

+0

也getStatusLine爲你提供StatusLine,然後你必須將它轉換爲字符串 –

相關問題