HTTP requests use TCP as an underlying protocol, so it is similar to using sockets. In Android if you put any network code on the main thread you will get this exception NetworkOnMainThreadException.
This is an example on how to safely make an HTTP request in Android:
Thread httpThread = new Thread(new Runnable() {
@Override
public void run() {
try {
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 5000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 7000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(url);
httpResponse = httpClient.execute(httpPost);
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
System.out.println(statusCode);
if (statusCode == 200) {
//success
}else{
//fail
}
} catch (Exception exception) {
Log.e("", exception.toString());
}
}
});
httpThread.start();