I've been struggling with this for a while now. I'm trying to perform get/post request with the Socket.connct
public String sendPostRequest(final String istr, final String data) {
response = null;
final boolean[] flag = new boolean[]{false};
Socket.connect(ipaddr, port, new SocketConnection() {
@Override
public void connectionError(int errorCode, String message) {
System.out.println("Error: "+ipaddr+" "+port);
}
@Override
public void connectionEstablished(InputStream is, OutputStream os) {
try {
if(isConnected()) {
os.write(("POST /"+istr+" HTTP/1.1\r\nContent-Length: "+data.length()+"\r\n\r\n"+data+"\r\n").getBytes());
byte[] b;
int numread;
StringBuilder lsb = new StringBuilder(100);
do
{
b = new byte[1024];
numread = is.read(b);
if( numread != -1 )
{
lsb.append(new String(b));
}
}
while( numread == 1024 );
response = lsb.toString();
}
}catch(IOException e) {
System.out.println("Network Read/Write Exception:");
}finally{
synchronized (flag) {
flag.notify();
}
try{
is.close();
}catch(IOException e) {};
}
}
});
synchronized (flag) {
try {
flag.wait();
} catch (InterruptedException e) {
}
}
return response;
}
This works with the simulator and I works on one android phone, but my other one hangs. Is there a way I can run the Socket on the same thread? Or is there a better way to run the synchronization?
On a side note before I was having and issue where it would hang on read instead of return -1 hence numread == 1024. Is that a bug?
I would appreciate any help on this. I have put in quite sometime messing around with it.
Thanks