Reputation: 1
I would like to send HTTP requests from my android app when pushing a button to an ESP8266 which is waiting for any webpage to be accessed, however i would prefer if my android app didn't actually open the webpage but rather just "send an HTTP Request"
Right now I'm using;
startActivity(new Intent(Intent.ACTION_QUICK_VIEW, Uri.parse("http://192.168.1.201/onled")));
and it is working, but obviously it is opening the webpage...
Anyone have a good suggestion on how to solve my problem? i am new at java.
Upvotes: 0
Views: 4176
Reputation: 3922
You should create the HTTP connection and HTTP request.
You can do it in a few ways:
HttpURLConnection
available natively in the Java - see this tutorial for details: https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/Please remember that sending HTTP request is non-deterministic operation and you should execute it in a separate, non-UI thread to keep UI unblocked. You can do it via AsyncTask, which is the simplest solution, but you can also use RxJava with RxAndroid or other approaches.
Upvotes: 0
Reputation: 63
new AsyncTask<Void,Void,Void>(){
private Exception exception;
@Override
protected Void doInBackground(Void... voids) {
try{
URL url= new URL("http://yourserveraddress/resource.extension");
HttpURLConnection con= (HttpURLConnection) url.openConnection();
//write additional POST data to url.getOutputStream() if you wanna use POST method
}catch (Exception ex){
this.exception=ex;
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}.execute();
Upvotes: 2
Reputation: 1614
There are many ways to send HTTP Requests from an app. For example using HttpURLConnection
with GET
method you can proceed as follows:
StringBuilder content = new StringBuilder();
try {
URL u1 = new URL(url);
HttpURLConnection uc1 = (HttpURLConnection) u1.openConnection();
if (uc1.getResponseCode()==HttpURLConnection.HTTP_OK) {
InputStream is = uc1.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line;
while ((line = br.readLine()) != null) {
content.append(line).append("\n");
}
}//other codes
You can find simplified ways to do so with Google most sophisticated methods:
Upvotes: 0