问题
In my android app, I have a listener thread which listens for anything posted over a server socket. Once something is posted (I use HttpRequester tool to POST any message), I get the input stream. I am able to see my json inside the input stream but cannot find a way to parse to get the json object out of it.
Here is my code sample doing it:
iMessageListenerThread = new Thread() {
public void run(){
// wait till user connects to server
try
{
iServerSocket = new ServerSocket();
iServerSocket.setReuseAddress(true);
iServerSocket.bind(new InetSocketAddress(mPort));
Log.d(TAG,"Server Socket opened" );
try {
for (;;) {
Socket ss = iServerSocket.accept(); // unblocks when connection is requested
// test if something received, if so, display this
InputStream localInputStream = ss.getInputStream();
if(localInputStream == null){
Log.d(TAG,"LOCAL INPUT STREAM NULL" );
continue;
}
//localInputStream = new GZIPInputStream(localInputStream);
String resultstring = convertStreamToString(localInputStream);
-----
-----
private String convertStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line+"\n");
total.append(line);
}
} catch (Exception e) {
Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
}
return total.toString();
}
In the HttpRequester tool, i put the following url: http://xxx.xxx.xx.xxx:8000/powerstate
and in the content section, I put this json:
{"powerstate":"on"}
This is my response string containging the json object:
I/RecorderService( 1518): ...resultstring : POST /powerstate HTTP/1.1
I/RecorderService( 1518): POST /powerstate HTTP/1.1Host: 192.168.21.240:8000
I/RecorderService( 1518): Host: xxx.xxx.xx.xxx:8000User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0
I/RecorderService( 1518): User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:30.0) Gecko/20100101 Firefox/30.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
I/RecorderService( 1518): Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-US,en;q=0.5
I/RecorderService( 1518): Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflate
I/RecorderService( 1518): Accept-Encoding: gzip, deflateContent-Type: application/json; charset=UTF-8
I/RecorderService( 1518): Content-Type: application/json; charset=UTF-8Content-Length: 19
I/RecorderService( 1518): Content-Length: 19Connection: keep-alive
I/RecorderService( 1518): Connection: keep-alivePragma: no-cache
I/RecorderService( 1518): Pragma: no-cacheCache-Control: no-cache
I/RecorderService( 1518): Cache-Control: no-cache
I/RecorderService( 1518): {"powerstate":"on"}
Can someone help me to know how to extract json object from this inputstream
来源:https://stackoverflow.com/questions/27508283/how-to-parse-server-socket-input-stream-to-get-json-object