简体   繁体   中英

Split string based on new line android

I have File which contain network traffic and I want to split POST request to two string header and body. I have problem with this.

        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);
            }


        }

May I know what is the problem with my code? I con't split them based on "\\r\\n\\r\\n". I tried many combination but I don't get it. Here is My text file contains:

  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

You can use bufferReader insted as it reads the file line by line by default. You just have to declare the list and add the lines to it . Try the following code

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM