2017-09-05 37 views
0

我有包含網絡流量的文件,我想將POST請求拆分爲兩個字符串頭和正文。我有這個問題。基於新行的拆分字符串android

 sc.useDelimiter(" ========================="); 
     String cellsbody=null; 
     String cellsheader= null; 

     String[] line1 = new String[2]; 

     Map<String, String> finalParseHeader = new HashMap<String, String>();; 
     while (sc.hasNext()) { 

      line1 = sc.next().split("\r\n\r\n"); 
      if(line1.length >= 2) { 
       cellsheader = line1[0]; 
       cellsbody = line1[1]; 
       Log.d("Post_Header", cellsheader); // Header Part 
       Log.d("Post_Body", cellsbody); // Body Part 
      }else{ 
       cellsheader = line1[0]; // Handle GET when there is no body 

       Log.d("GET_header", cellsheader); 
      } 


     } 

我可以知道我的代碼有什麼問題嗎? 我不會根據「\ r \ n \ r \ n」來拆分它們。我嘗試了很多組合,但我不明白。 這裏是我的文本文件包含:

POST /location/update?ts=1504152243110 HTTP/1.1 
    X-Cc-Device: 
    imei=37abc5afce16b603&model=Huawei&language=en&version=325&os=Android 
    23&service=1&api=1.0.0&wifi=1 
    Cookie: u=; s= 
    Content-Type: application/x-www-form-urlencoded 
    Content-Length: 40 
    Host: hk.meecha.net 
    Connection: Keep-Alive 
    Accept-Encoding: gzip 
    User-Agent: okhttp/3.5.0 

isactived=1&lat=0.0&lng=0.0&haveredbag=1 <= Here the body for Post request 
    ========================= 
GET /easemob/server.json? 
sdk_version=3.3.2&app_key=chatcat%23chatcat&file_version=1 HTTP/1.1 
Host: rs.easemob.com 
Connection: Keep-Alive 
User-Agent: Easemob-SDK(Android) 3.3.2 
+0

要分割的字符串來自Windows服務器嗎? – Tom

+0

no.it來自文件。我發現,很難從服務器分離緩衝區,因爲大的請求可以分成許多緩衝區數組,這使我很難分割標題和主體。我會感激你的小費 – kaloon

回答

0

您可以使用bufferReader insted的,因爲它逐行讀取文件中的行默認。你只需要聲明列表並添加行就可以了。請嘗試以下代碼

ArrayList<String> itemList = new ArrayList<String>(); 
BufferedReader sc = new BufferedReader(new 
InputStreamReader(yourfilepath)); 
String str; 
while ((str = sc.readLine()) != null) { 
itemList.add(str); 
} 
in.close();