1

I'm using ServerSocket to listen to a certain port on an Android app in order to get a response from a server. When the server sends the http response I receive it as a socket and then I use the Input Stream to get the data.

Any way, everything works great and I get the Http Response but as a string (because I'm reading the Input Stream and then decode it to string):

GET /?code={Some code} HTTP/1.1
Host: localhost:9004
Connection: keep-alive
.
.
.
{More headers}

What I need is to parse the code (first row) but I don't want to process the string by my self. I'm sure there's a easier way.

ServerSocket serverSocket = new ServerSocket(9004);
serverSocket.setReuseAddress(true);
serverSocket.setReceiveBufferSize(1500);
if(!serverSocket.isBound()) {
    SocketAddress localAddress = new InetSocketAddress(9004);
    serverSocket.bind(localAddress);
}

Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
byte[] buffer = new byte[1024];
int count = is.read(buffer);
String response = new String(buffer, "UTF-8");

// What should I do here??

serverSocket.close();

Thanks a lot!

Cœur
  • 37,241
  • 25
  • 195
  • 267
Tsikon
  • 324
  • 1
  • 3
  • 14

1 Answers1

0

I assume that you want the part between brace, so i will use this regular expression with this Matcher: "\\{(.*?)\\}" .

For example:

String response = new String(buffer, "UTF-8");
Pattern pattern = Pattern.compile("\\{(.*?)\\}");
Matcher matcher = pattern.matcher(response);
if (matcher.find())
{
    System.out.println(matcher.group(1));
}

I followed the example of this StackOverflow link.

Community
  • 1
  • 1
JJ86
  • 5,055
  • 2
  • 35
  • 64
  • Thanks JaAd, I appreciate it. I was more focused on using something else rather than parsing the string on my own. I can find the code by simply using String.indexof and String.substring but I want to avoid that. I'm thinking about some class that receives that response string and make an httpresponse object from it. – Tsikon Mar 08 '14 at 14:05
  • @Tsikon i was writing the same think, but using String.indexOf or String.subString or even StringTokenizer is a little barbarian! So the response you get is used for another http request? – JJ86 Mar 08 '14 at 14:18
  • What I'd like to know is if there's another way to get the response (i.e. as an HttpResponse object) or alternatively to have this response string to be processed by some other SDK and get the value I need from a method of this SDK. Just like when you parse a json string into a JSONObject. – Tsikon Mar 08 '14 at 19:40
  • @Tsikon by SDK you intend a class or a library i guess. By the way try this: http://developer.android.com/reference/org/apache/http/client/utils/URLEncodedUtils.html; or this answer http://stackoverflow.com/questions/13592236/parse-the-uri-string-into-name-value-collection-in-java . – JJ86 Mar 11 '14 at 11:05