Skip to content Skip to sidebar Skip to footer

Make Simply Http Request And Receive The Content

I have found a working code for makeing simply HTTP requests here, from How can I make a simple HTTP request in MainActivity.java? (Android Studio) and I am going to post it below

Solution 1:

Add this to your onPostExecute(String result) call

protectedvoidonPostExecute(String result) {
        // this is executed on the main thread after the process is over// update your UI here    setMyData(result);
    }

And then fill your textfield or whatever other data you need to update.

privatevoidsetMyData(String result){
        textView3.setText(result); 
    }

Solution 2:

Where exactly are you stuck? Your code mostly correct although you may need to rearrange it slightly. Your scope is a bit off and your commented code almost gets there. See below

protectedString doInBackground(String... urls) {
    String content = "", line = "";
    HttpURLConnection httpURLConnection;
    BufferedReader bufferedReader;
    URL url;

    try {
        for(String uri : urls) {
            url = new URL(uri);
            url = new URI(url.toURI().getScheme(), url.getAuthority(), url.getPath(), "pin=" + URLEncoder.encode("&OFF1", "UTF-8"), null).toURL();

            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.connect();


            bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            while ((line = bufferedReader.readLine()) != null) {
                content += line + System.lineSeparator();
            }
        }
     } catch (Exception e) {
         e.printStackTrace();
     } finally {
         try {
            bufferedReader.close();
         } catch(Exception e) {
             e.printStackTrace();
         }
     }

     return content;

}

That will return a String representation of your page. If the page contains HTML it will return text/html, if it contains text it will return just text.

Then as a previous user stated you can set the response on your GUI

protectedvoidonPostExecute(String result) {
    textView3.setText(result);
}

The above example will technically work. However, I would highly recommend using http://loopj.com/android-async-http/ over HttpURLConnection. Your code will be much nicer which will matter down the line.

The code I sent you assumes that the parameter is always pin=OFF1 because it's more a proof of concept

Post a Comment for "Make Simply Http Request And Receive The Content"