I can not get any data from the URL

0

I'm working on a project where I have to make an App that fetches information from the database via Json. I have done dozens of tutorials and I always end up not being able to receive a response from Server and does not even get any requests to Server .

Here is the code of the last one I did and hoped to achieve:

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 I also had the method POST but since I just want to go get information, I took it.

What's wrong with me? What other solution can be used to solve this problem?

    
asked by anonymous 25.02.2015 / 18:14

1 answer

0

The problem was that the host has an unsafe certificate and the android in a way did not want to move forward. The following solution is not the right or the safest (as I read it on the web) but for me it works 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);

}
    
27.02.2015 / 16:05