2014-01-08 36 views
0

我正在开发一个文件管理器Android应用程序,它通过POST方法将base64编码文件发送到Web服务器。在服务器端,cgi perl脚本获取字符串,解码并保存到文件中。问题是无法建立套接字连接,并且Apache访问日志中没有数据条目。请分享任何想法,以下是源代码:通过HTTP和POST发送查询字符串的Android应用程序

“i”是类Item的对象 - 即从文件管理器中选择的文件。

Item i = adapter.getItem(position); 我正在将“我”传递给sendFile方法。

private void sendFile(Item i) { 
    try { 
     File inFile; 
     DataInputStream dis; 
     String queryString, encodedData, headerPart1, headerPart2, dataBundle; 
     byte[] fileData; 
     int contentLength; 
     String host = "192.168.100.2"; 

     inFile = new File(i.getPath()); 
     fileData = new byte[(int) inFile.length()]; 
     dis = new DataInputStream(new FileInputStream(i.getPath())); 
     dis.readFully(fileData); 
     dis.close(); 

     encodedData = Base64.encodeToString(fileData, Base64.NO_WRAP); 

     AccountManager accountManager = AccountManager 
       .get(getBaseContext()); 
     Account account = getAccount(accountManager); 

     queryString = account.name + "^" + i.getName() + "^" + encodedData; 

     headerPart1 = "POST /cgi-bin/grabber.cgi HTTP/1.1\r\n" + "Host: " 
       + host + "\r\n" + "User-Agent: Tposter\r\n" 
       + "Content-Length: "; 
     headerPart2 = "Content-Type: text/plain\r\n" 
       + "Accept-Charset: UTF-8\r\n\r\n"; 

     contentLength = queryString.length(); 
     dataBundle = headerPart1 + contentLength + "\r\n" + headerPart2 
       + queryString; 

     // Create file uploader thread 
     FileUploader fileUploader = new FileUploader(dataBundle); 
     fileUploader.start(); 
     Toast.makeText(this, "File sent!", Toast.LENGTH_LONG).show(); 
     finish(); 

    } catch (Exception e) { 
     Log.e("send ERROR in file FileChooser.class ", e.getMessage()); 
    } 
} 

FileUploader.java

public class FileUploader extends Thread { 

PrintWriter printWriter; 
SocketAddress sockAddr; 
Socket socket; 
int port = 80; 
String host = "192.168.100.2"; 

public FileUploader(String dataBundle) { 
    try { 
     sockAddr = new InetSocketAddress(host, port); 
     socket = new Socket(); 
     socket.setSoTimeout(3000); 
     socket.connect(sockAddr, 5000); 
     if (socket.isConnected()) { 
      Log.w("Connected! ", dataBundle); 

      printWriter = new PrintWriter(new OutputStreamWriter(
        socket.getOutputStream())); 

      printWriter.println(dataBundle); 
      printWriter.flush(); 
      printWriter.close(); 
      socket.close(); 
     } 
    } catch (IOException e) { 
     Log.e("socket ERROR in file fileUploader.class ", e.getMessage()); 
    } 
} 

}

[调试截图]:(http://postimg.org/image/6upsjregb/

+1

为什么你会使用套接字做基于REST通信时,[机器人有自带的几个HTTP客户端(http://android-developers.blogspot.co.nz/2011/09/androids-http- clients.html)? – panini

+0

为什么你base64编码文件数据?我建议按原样发送原始文件数据。为了帮助实现这个目的,将'account.name'移动到一个自定义的HTTP头,比如'X-AccountName',并将'i.getName()'移动到'Content-Type'头的'name'参数。然后,您可以使用HTTP 1.1的'Transfer-Encoding:chunked'头文件(并省略Content-Length头文件),以便可以读取并发送原始文件数据块以减少内存使用量,并且不会将整个文件读入记忆了。 –

+0

我正在对文件进行编码以便通过HTTP发送二进制文件,但请专注于此问题。我会尝试HTTP客户端。谢谢。 – X0rrify

回答

0

我使用的HttpClient来实现这一目标。下面的例子发送并等待从我的服务器接收JSON数据。

private String postPullData(JSONObject json, String URL) throws JSONException { 
    HttpClient httpclient; 
    int CONNECTION_TIMEOUT = 20*1000; 
    int WAIT_RESPONSE_TIMEOUT = 20*1000; 
    HttpPost httppost = new HttpPost(URL); 

    String Error = "SCOMM Error: "; 
    JSONArray postjson; 
    URL url = null; 

    int sdkVersion = Build.VERSION.SDK_INT; 

    /* 
    * according to the Android docs, Android 3.0+ should use URLConnection 
    * but I can't get that to work. For now, keep using HttpConnection 

    if (sdkVersion < Build.VERSION_CODES.HONEYCOMB) { 
    */ 
     // use the older HttpClient 

     HttpParams httpParameters = new BasicHttpParams(); 
     HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT); 
     HttpConnectionParams.setSoTimeout(httpParameters, WAIT_RESPONSE_TIMEOUT); 
     HttpConnectionParams.setTcpNoDelay(httpParameters, true); 

     httpclient = new DefaultHttpClient(httpParameters); 


     try { 

      postjson = new JSONArray(); 
      postjson.put(json); 

      // Post the data: 
      httppost.setHeader("json", json.toString()); 
      httppost.getParams().setParameter("jsonpost", postjson); 

      // Execute HTTP Post Request 
      System.out.print(json); 
      HttpResponse response = httpclient.execute(httppost); 

      // for JSON: 
      if (response != null) 
      { 
       InputStream is = response.getEntity().getContent(); 
       BufferedReader reader = new BufferedReader(
         new InputStreamReader(is)); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 
       try { 
        while ((line = reader.readLine()) != null) { 
        sb.append(line + "\n"); 
        } 
       } catch (IOException e) { 
        Error += " IO Exception: " + e; 
        Log.d("SCOMM", Error); 
        e.printStackTrace(); 
        return Error; 
       } finally { 
        try { 
         is.close(); 
        } catch (IOException e) { 

         Error += " closing connection: " + e; 
         Log.d("SCOMM", Error); 
         e.printStackTrace(); 
         return Error; 
        } 
       } 

       return sb.toString(); 

<snip> 
相关问题