How to make Sync or Async HTTP Post/Get

前端 未结 3 1022
北荒
北荒 2020-12-19 01:21

I need Sync or Async HTTP Post/Get to get HTML data from Web-Service. I search this whole internet but I can\'t give good result.

I tried to use this examples:

3条回答
  •  盖世英雄少女心
    2020-12-19 01:33

    **Async POST & GET request**
    
    public class FetchFromServerTask extends AsyncTask {
        private FetchFromServerUser user;
        private int id;
    
        public FetchFromServerTask(FetchFromServerUser user, int id) {
            this.user = user;
            this.id = id;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            user.onPreFetch();
        }
    
        @Override
        protected String doInBackground(String... params) {
    
            URL urlCould;
            HttpURLConnection connection;
            InputStream inputStream = null;
            try {
                String url = params[0];
                urlCould = new URL(url);
                connection = (HttpURLConnection) urlCould.openConnection();
                connection.setConnectTimeout(30000);
                connection.setReadTimeout(30000);
                connection.setRequestMethod("GET");
                connection.connect();
    
                inputStream = connection.getInputStream();
    
            } catch (MalformedURLException MEx){
    
            } catch (IOException IOEx){
                Log.e("Utils", "HTTP failed to fetch data");
                return null;
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }
    
        protected void onPostExecute(String string) {
    
            //Do your own implementation
        }
    }
    
    
    ****---------------------------------------------------------------***
    
    
    You can use GET request inn any class like this:
    new FetchFromServerTask(this, 0).execute(/*Your url*/);
    
    ****---------------------------------------------------------------***
    

    For Post request just change the : connection.setRequestMethod("GET"); to

    connection.setRequestMethod("POST");

提交回复
热议问题