50% Off/-

50% Off/-

Php

50% Off/-

50% Off/-

Web

50% Off/-

50% Off/-

Android Simple Http Get Request

06-05-2019

HttpGetRequestTask

import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpGetRequestTask extends AsyncTask<String, Integer, String> {
    private RequestResponseHandler requestResponseHandler;
    public HttpGetRequestTask(RequestResponseHandler requestResponseHandler) {
        this.requestResponseHandler=requestResponseHandler;
    }
    
    protected String doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);
            HttpURLConnection connection = 
                (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.connect();
            BufferedReader rd = 
                new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                content.append(line).append("\n");
            }
            rd.close();
            connection.disconnect();
            return content.toString();
        } catch (IOException e) {
            return "";
        }
    }
    
    protected void onProgressUpdate(Integer... progress) {
    }
    
    protected void onPostExecute(String result) {
        // this is executed on the main thread after the process is over
        // update your UI here
        this.requestResponseHandler.response(result);
    }
}

RequestResponseHandler

public interface RequestResponseHandler {
    void response(String result);
}

Calling HttpGetRequestTask

new HttpGetRequestTask(new RequestResponseHandler() {
    @Override
    public void response(String result) {
        try {
            JSONArray reader = new JSONArray(result);
            for (int i = 0; i < reader.length(); i++) {
                JSONObject jsonObject = reader.getJSONObject(i);
                int id = jsonObject.getInt("id");
                String name = jsonObject.getString("name");
                String packageName = jsonObject.getString("package");
                MenuItem menuItem = myAppsMenu.add(100, id, i, name);
                
                View actionView = new View(getApplicationContext());
                actionView.setTag(packageName);
                menuItem.setActionView(actionView);
            }
            
        } catch (JSONException e) {
            e.printStackTrace();
        }
        
    }
    }).execute("http://boyuzatma.evhediyesial.com/api/v1/advertisements/" + getPackageName());

© 2019 Tüm Hakları Saklıdır. Codesenior.COM