1

I am creating an app for electricity recharge payment. i want the app to work like this., a customer enters his/her meter number together with the amount to be paid. After clicking the submit button,this info has to be sent to the Service Provider using a POST Request via the OKHTTP3 protocol. I wrote the code below and its showing nothing when i click the Submit Button. Please help.

package googleplayservices.samples.android.com.whitney.shumba;

import android.content.Intent;
import android.renderscript.RenderScript;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Zesa extends AppCompatActivity {
  private TextInputEditText txtinputmeter,txtinputamount;
  private Button submit;
  private TextView json;


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

        json = (TextView) findViewById(R.id.jsonTV);
        txtinputmeter = (TextInputEditText) findViewById(R.id.txt_input_meter);
        txtinputamount = (TextInputEditText) 
       findViewById(R.id.txt_input_amount);
        submit = (Button) findViewById(R.id.submitButton);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Okhttp3 client network request
                OkHttpClient client = new OkHttpClient();
                String url = "https://www.shumbapay.com";
                Request request = new Request.Builder()
                        .url(url)
                        .build();

                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws 
                                  IOException {
                        if(response.isSuccessful()){
                            final String myResponse = response.body().string();

                            Zesa.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    json.setText(myResponse);
                                }
                            });
                        }
                    }
                });
                Submit();
            }

            private void Submit() {
                startActivity(new Intent(Zesa.this, Payzesa.class));
            }
        });
    }

}
Ali Ahmed
  • 2,130
  • 1
  • 13
  • 19

5 Answers5

1

I will give you a solution to your problem along with a general explanation as of how to use OKHTTP3 POST request in general, as you might need to expand your project in the future too.

  • First Step, you need to convert your data that you want to send into a JSON object. This will make your code cleaner and more maintainable. To do that, create a java class for your data that needs to be sent. In your case the java class will look like this:

     public class Data{
        @Expose
        private String meter;
        @Expose
        private String amount;
        //Add a constructor and getters + setters
      }
    

Then, add the following line to the build.gradle of your module:

implementation 'com.google.code.gson:gson:2.8.4'

This allows you to use the gson library to automatically convert your java object into a JSON object.

Then create the JSON object which will contain the data you want to send. This is done as follows:

    Data data=new 
      Data(txtinputmeter.getText.toString(),txtinputamount.getText.toString());
      Gson gson = new GsonBuilder().serializeNulls().create();
       String JSONObjectString = gson.toJson(data);
  • Second step, Create the OKHTTP Post method as follows:

     public static String doPostOkHttp(String URL, String jsonObject) {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON, jsonObject);
        Request request = new Request.Builder()
                .url(URL)
                .post(body)
                .header("Content-type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.code() == 200) {
               Log.d("Server response 200",response.body().string());
                return response.body().string();
            } else {
               Log.d("Server response Error","ERROR");
                return "Server response Error";
            }
        } catch (IOException e) {
    
        }
        return "Server response Error";
    }
    

The above method allows you to send a message to the server and receive a response from it if it does have a body.

  • Third step, is to send the JSON object which contains your data This is done as follows:

    doPostOkHttp("your URL", JSONObjectString );
    

Then monitor your logcat and see what the Server response looks like.


It is good practise to run the doPostOkHttp in a separate thread. As long as you understand the above code, you can easily use the Callback technique which you were using in your code.

If you still face problems, then go through this very simple tutorial step by step so you understand everything about how to use Post in OKHTTP: http://www.vogella.com/tutorials/JavaLibrary-OkHttp/article.html

Mena
  • 3,019
  • 1
  • 25
  • 54
0

You're displaying a new Activity after sending your request. So, the current Activity can't retrieve the server response... You have to put your Submit() method after receiving the response.

Bruno
  • 3,872
  • 4
  • 20
  • 37
0

According to your coding you are navigating to Payzesa.class before the response

so put the intent or the action inside this

 @Override
                public void onResponse(Call call, Response response) throws 
                              IOException {
                    if(response.isSuccessful()){
                        final String myResponse = response.body().string();

                        Zesa.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                json.setText(myResponse);
                            }
                        });
                    }
                }
            });
Jins Lukose
  • 699
  • 6
  • 19
  • thank you Jins Lukose. Let me do likewise and give you the feedback – WhitneyFruit Oct 29 '18 at 10:16
  • i want the response to be displayed on the current activity.(the response will be a verification of the account details in JSON format), then the user navigates to the PayZesa activity to select the mode of payment – WhitneyFruit Oct 29 '18 at 10:29
  • @WhitneyFruit actually you are not passing the meter number and amount. so that you are not getting response. do you have any parameters to pass the data to server – Jins Lukose Oct 29 '18 at 10:32
  • how do i pass the 2 (meter number and amount)? – WhitneyFruit Oct 29 '18 at 10:36
  • @WhitneyFruit https://stackoverflow.com/questions/34826520/how-to-send-post-parameters-dynamically-or-in-loop-in-okhttp-3-x-in-android check this you will understand – Jins Lukose Oct 29 '18 at 10:38
0

Use below function for POST call in OKHTTP3

 public void postMethod(String url, String id, String postParm) {
    try {
        try {

            //If you have multiple images
            MultipartBody.Builder multipartBody = new MultipartBody.Builder().setType(CONTENT_TYPE);
            final MediaType MEDIA_TYPE = MediaType.parse("image/*");
            int urlSize = image.size();
            for (int i = 0; i < urlSize; i++) {
                String imageUrls = image.get(i);
                File sourceFile = new File(imageUrls);
                if (sourceFile.exists()) {
                    multipartBody.addFormDataPart("image", sourceFile.getName(), RequestBody.create(MEDIA_TYPE, sourceFile));
                }
            }

            RequestBody postData = multipartBody
           .addFormDataPart("postParm", postParm).build();
            Request request = new Request.Builder().url(url).post(postData).build();
            executeRequest(url, request);

        } catch (Exception e) {
            Log.e("Error: " + e.getLocalizedMessage());
        }


    } catch (Exception e) {
        e.printStackTrace();
    }

}
Arbaz.in
  • 1,478
  • 2
  • 19
  • 41
0

You can use Retrofit with OkHttp3.

First you need to create OkHttp client.

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(Constants.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .cache(cache)
                .readTimeout(0, TimeUnit.SECONDS)
                .connectTimeout(0, TimeUnit.SECONDS)
                .build();

Use OkHttp client to build Retrofit.

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(YOUR_BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(JacksonConverterFactory.create(objectMapper))
                .build();

Next, you have to create an interface which will contain RESTapi methods

public interface RESTApi {
  //all api methods will go here
}

RESTApi restApi = retrofit.create(RESTApi.class);
Shrikant
  • 579
  • 1
  • 5
  • 21