2013-11-25 157 views
0

目前,我從android應用程序發送一個用戶名作爲參數到我的servlet。現在我想從android應用程序發送文本文件到我的servlet。有可能嗎? 這裏的示例代碼,我試過用Http發送用戶名。通過http發送文本文件android

 try 
     { 
     URL url = new URL("http:/xx.xxx.xxx.x/sample?user=admin"); // File as parameter 
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
      InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
      BufferedReader r = new BufferedReader(new InputStreamReader(in)); 
      String x = ""; 
      String total = ""; 
      int i=0; 
      ArrayList<String> content = new ArrayList(); 
      while((x = r.readLine()) != null) 
      { 
         content.add(x); 

      } 
      in.close(); 
      r.close(); 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
      Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show(); 
     } 

上面的代碼工作正常,如何通過其存儲在我的SD卡作爲提前參數到servlet?.thanks文本文件。

+2

雅很可能是我們可以將文件發送到服務器,請參考以下鏈接HTTP://reecon.wordpress。 com/2010/04/25 /上傳文件到http-server-using-post-android-sdk/ – prakash

+0

而不是圖像放置你的文本文件 – prakash

回答

0

這裏是一些代碼,但我強烈建議上傳數據通過POST請求而不是GET請求:

private void sendFileThroughHTTP(File file) { 
    try { 
     Uri uri = new Uri.Builder().scheme("http").encodedAuthority("xx.xxx.xxx.x") 
       .path("sample") 
       .appendQueryParameter("user", "admin") 
       .appendQueryParameter("file", fileToString(file)) 
       .build(); 
     HttpGet get = new HttpGet(uri.toString()); 

     HttpClient client = new DefaultHttpClient(); 
     client.execute(get); 
    } catch (ClientProtocolException e) { 
     Log.e("SOME_TAG", Log.getStackTraceString(e)); 
    } catch (IOException e) { 
     Log.e("SOME_TAG", Log.getStackTraceString(e)); 
    } 
} 

private String fileToString(File file) { 
    String resultString = ""; 
    FileReader fileReader = null; 
    if (file != null && file.isFile()) { 
     try { 
      fileReader = new FileReader(file); 
      BufferedReader reader = new BufferedReader(fileReader); 
      StringBuilder stringBuilder = new StringBuilder(); 
      String temp; 
      while ((temp = reader.readLine()) != null) { 
       stringBuilder.append(temp); 
      } 
      resultString = stringBuilder.toString(); 
     } catch (FileNotFoundException e) { 
      Log.e("SOME_TAG", Log.getStackTraceString(e)); 
     } catch (IOException e) { 
      Log.e("SOME_TAG", Log.getStackTraceString(e)); 
     } finally { 
      try { 
       if (fileReader != null) { 
        fileReader.close(); 
       } 
      } catch (IOException e) { 
       Log.e("SOME_TAG", Log.getStackTraceString(e)); 
      } 
     } 
    } 
    return resultString; 
}