He escrito el siguiente código para publicar y obtener datos del servidor usando okhttp pero no funciona. En NewTest.java

public class NewTest extends AppCompatActivity {

   TextView txtJson;
    Button btnOkay;

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

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

      findViewById(R.id.txtJson)).getText().toString());

        assert (findViewById(R.id.btnOkay)) != null;
        (findViewById(R.id.btnOkay)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new TaskPostWebService("url written here").execute(((TextView) findViewById(R.id.txtJson)).getText().toString());
            }
        });

    }

    private class TaskWebServiceGet extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {

            try {

                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder()
                        .url(params[0])
                        .build();

                Response response = client.newCall(request).execute();

                String responseJson = response.body().string();
                Log.i("@", "" + responseJson);
            }
            catch (Exception e){

                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }

    private class TaskPostWebService extends AsyncTask<String,Void,String> {
        private String url;
        private ProgressDialog progressDialog;

        public TaskPostWebService(String url ){

            this.url = url;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(NewTest.this,"","");
        }

        @Override
        protected String doInBackground(String... params) {

            String fact = "";
            try {

                OkHttpClient client = new OkHttpClient(); 

                RequestBody body = new FormBody.Builder()
                         .add("\"nonce\" : \"G9Ivek\",", params[0])
                        .add("\"iUserId \": \"477\",", params[1])

                          .build(); 

                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();

                Response response = client.newCall(request).execute(); // hits server

                String json = response.body().string(); // server gives response

                ObjectMapper mapper = new ObjectMapper();
                Map<String,String> map = mapper.readValue(json, new TypeReference<Map>() { // convert json to object
                });

                if(map != null){

                    fact = map.get("gruesomeFact");

                }
                Log.i("@",""+json);
            }
            catch (Exception e){
                e.printStackTrace();
            }
            return fact;
        }
      @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            TextView text = (TextView) findViewById(R.id.txtJson);
            text.setText(s);
            progressDialog.dismiss();
        }
    }

}

Recibo un mensaje de Acceso denegado.

¿Alguien puede decirme qué está mal?

0
Rujuta 22 jul. 2016 a las 14:02

2 respuestas

La mejor respuesta

La respuesta al código es la siguiente. funcionó. Ahora quiero mostrar la respuesta en listview. ¿Como hacer esto?

* / public class NewTest extiende AppCompatActivity {

    TextView txtJson;
    Button btnOkay;

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

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


        assert (findViewById(R.id.btnOkay)) != null;
        (findViewById(R.id.btnOkay)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

              new TaskPostWebService("written url here").execute(((TextView)
findViewById(R.id.txtJson)).getText().toString());

            }
        });

    }
    private class TaskPostWebService extends AsyncTask<String,Void,String> {

        private String url;
        private ProgressDialog progressDialog;
        private JSONParser jsonParser;

        public TaskPostWebService(String url ){

            this.url = url;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(NewTest.this,"","");
        }

        @Override
        protected String doInBackground(String... params) {

         String fact = "";
            try {

                final MediaType JSON = MediaType.parse("application/json");

                android.util.Log.e("charset", "charset - " + JSON.charset());
                OkHttpClient client = new OkHttpClient();

//Create a JSONObject with the data to be sent to the server
                final JSONObject dataToSend = new JSONObject()
                        .put("nonce", "G9Ivek")
                        .put("iUserId", "477");

                android.util.Log.e("data - ", "data - " + dataToSend.toString());

//Create request object
                Request request = new Request.Builder()
                        .url("written url here")
                        .post(RequestBody.create(JSON, dataToSend.toString().getBytes(Charset.forName("UTF-8"))))
                        .addHeader("Content-Type", "application/json")
                        .build();

                android.util.Log.e("request - ", "request - " + request.toString());
                android.util.Log.e("headers - ", "headers - " + request.headers().toString());
                android.util.Log.e("body - ", "body - " + request.body().toString());

//Make the request
                Response response = client.newCall(request).execute();
                android.util.Log.e("response", " " + response.body().string()); //Convert the response to String
                String responseData = response.body().string();

//Construct JSONObject of the response string
                JSONObject dataReceived = new JSONObject(responseData);

//See the response from the server
                Log.i("response data", dataReceived.toString());
            }
            catch (Exception e){
                e.printStackTrace();
            }
            return fact;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            TextView text = (TextView) findViewById(R.id.txtJson);
            text.setText(s); 
            progressDialog.dismiss();
        }
    }

Kindly tell me how to show response of this in listview. Thanks
0
Rujuta 27 jul. 2016 a las 10:29

Intente realizar la solicitud POST de la siguiente manera en su método doInBackground():

private final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient(); 

//Create a JSONObject with the data to be sent to the server
JSONObject dataToSend = new JSONObject()
    .put("nonce", "G9Ivek")
    .put("iUserId", "477");

//Create request object
Request request = new Request.Builder()
    .url(url)
    .post(RequestBody.create(JSON, dataToSend.toString()))
    .build();

//Make the request
Response response = client.newCall(request).execute();

//Convert the response to String
String responseData = response.body().string();

//Construct JSONObject of the response string
JSONObject dataReceived = new JSONObject(responseData);

//See the response from the server
Log.i("response data", dataReceived.toString());
0
Prerak Sola 25 jul. 2016 a las 12:14