I get no data from the URL

Asked

Viewed 81 times

0

I’m working on a project where I have to make an app that will fetch information from the database via Json. I’ve done dozens of tutorials and I always end up not being able to receive a reply from Server and not even get any request to the Server.

Here’s the code of the last one I did that I was hoping would work:

Json

{
    "Device": {
        "id": "1198",
        "activo": "1",
        "designacao": "alvaro-digisilent",
        "data_entrada": "2014-07-25",
        "username": "*****",
        "password_admin": "*******",
        "so": "Microsoft Windows",
        "so_versao": "7",
        "obs": "",
        "local_id": "4",
        "cliente_id": "1",
        "tipo_maquina_id": "2",
        "colaboradore_id": "148",
        "factura_id": "1"
    }
}

Mainactivity.java

public class MainActivity extends ListActivity {

    private ProgressDialog pDialog;

    //URL para ir buscar os Devices JSON
    private static String url = "<linkdapaginaquedáojson>";

    //Nomes dos JSON Nodes
    private static final String TAG_DEVICE = "Device";
    private static final String TAG_LOCAL = "local";
    private static final String TAG_FACTURA = "factura";

    //Devices JSONArray
    JSONArray devices = null;

    //Hashmap para a ListView
    ArrayList<HashMap<String, String>> deviceList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        deviceList = new ArrayList<HashMap<String, String>>();

        ListView listView = getListView();


        //Chamar a ASyncTask para ir buscar o JSON
        new GetDevice().execute();
    }

    //ASyncTask para receber o JSON ao fazer a HTTP Call
    private class GetDevice extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //Mostra a barra de progresso
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Espera que eu tambem esperei");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            //Criar uma instance da class Service Handler
            ServiceHandler sh = new ServiceHandler();

            //Faz um request ao url e recebe a resposta
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("MYLOG", "Response= " + jsonStr);

            if (jsonStr != null) {
                try {

                    //Criar um JSON Object
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    devices = jsonObj.getJSONArray(TAG_DEVICE);

                    JSONObject d = devices.getJSONObject(0);

                    String device = d.getString(TAG_DEVICE);
                    String local = d.getString(TAG_LOCAL);
                    String factura = d.getString(TAG_FACTURA);

                    //Hashmap temporario para apenas um device
                    HashMap<String, String> dev = new HashMap<String, String>();

                    dev.put(TAG_DEVICE, device);
                    dev.put(TAG_FACTURA, factura);
                    dev.put(TAG_LOCAL, local);

                    deviceList.add(dev);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            super.onPostExecute(result);

            //Dismiss da progress bar
            if(pDialog.isShowing())
                pDialog.dismiss();

            //update do parsed JSON para a listview
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, deviceList, R.layout.list_item, new String[]{TAG_DEVICE,
            TAG_FACTURA, TAG_LOCAL}, new int[]{R.id.name, R.id.factura, R.id.local});

            setListAdapter(adapter);
        }
    }
}

Servicehandler.java

public class ServiceHandler {

    static String response = null;
    public final static int GET = 1;

    public ServiceHandler() {

    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    /**
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
                                  List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;

    }
}

In the tutorial there was also the method POST but since I just want to get information, I took.

What is wrong with me? What other solution can be used to resolve this obstacle?

  • Peter, where does that title come from in English? Is it a mistake? Or is it a lack of translation?

  • I put it in, I didn’t know what title to give and because it’s the problem...

  • Start here: http://answall.com/questions/43288/como-fazer-uma-requisi%C3%A7%C3%A3o-http-get-data-and-reply-with-json/43294#43294

1 answer

0


The problem was that the host has an insecure certificate and the android somehow did not want to advance. The following solution is not the most correct or the safest (as I read on the web) but it serves me perfectly.

public void sslCertificates() {
    TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {

                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    //No need to implement.
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    //No need to implement.
                }
            }
    };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e)
    {
        System.out.println(e);
    }

    mTextView = (TextView) findViewById(R.id.mTextView);

    JsonObjectRequest request = new JsonObjectRequest("linklink", null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {

                    mTextView.setText(response.toString());

                }
            },

            new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    mTextView.setText(error.toString());
                }
            }
    );
    VolleyApplication.getInstance().getRequestQueue().add(request);

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.