Sending a POST request to a web server using OKHTTP3

okhttp post request with parameters
json parsing using okhttp in android
okhttp post json
okhttp get request with parameters
okhttp response
okhttp vs httpclient
okhttpclient https example
okhttp3 jar

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));
            }
        });
    }

}

Making http post requests using okhttp, Making http post requests using okhttp String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); new File("website/static/logo-square.png"))) .build(); Request request = new Request. public void send(DatadogHttpReporter. origin: Graylog2/graylog2-​server  Call call = okHttpClient.newCall(request); 4. Send Http Request Synchronously And Asynchronously. You can send http get or post request with OkHttp3 synchronously or asynchronously. When you send the request synchronously, you need to run the code in a child thread because the process may take long time.


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.

Using the OkHttp library for HTTP requests - Tutorial, To use OkHttp you need to create a Request object. Sending and receiving network calls test class which is more or less taken for the http://square.github.​io/okhttp/ website. newCall(request).execute(); return response.body().string(); } // post request code here public static final MediaType JSON  This article shows you how to use the OkHttp library to send an HTTP GET/POST requests and some frequent used examples.. P.S Tested with OkHttp 4.2.2


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);
                            }
                        });
                    }
                }
            });

OkHttp - How to send HTTP requests, This article shows you how to use the OkHttp library to send an HTTP GET/POST requests and some frequent used examples. P.S Tested with  Making http post requests using okhttp. { okhttp3.Request request = new okhttp3.Request.Builder() . post Uses request to connect a new web socket.


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();
    }

}

GET And POST request using OKHttp in Android Application , Response response = client.newCall(request).execute();. In above method, I also add header because in my server API it is required to send  In this tutorial, we are sending JSON as a request and getting also JSON as a response. To send POST request we need to create RequestBody Object and Pass it into Request Object. In the RequestBody object, we will pass Media type and post data as a string. Request Object is used to build your URL, POST data, Header(We can set Authorization token).


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);

How to do GET and POST requests in Android using OkHttp, In this tutirial you will know how to do GET and POST requests in Android. and add the following dependency, or check the OKHttp site for the latest updates. We can send POST request to server using following approach To make asynchronous calls, also create a Call object but use the enqueue method, and passing an anonymous callback object that implements both onFailure () and onResponse (). OkHttp creates a new worker thread to dispatch the network request and uses the same thread to handle the response.


Post method sending Json or text with OkHttp3 in Android, Its request/response API is designed with fluent builders and immutability. Post to a Server¶ charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, String json) As with auto-updating web browsers, staying current with HTTPS clients is an important defense against potential security problems. Finally, we create the request with the REST URI, the body we have just created and invoke the request. 3. Server side source code. This section describes an example of server side source code implemented for the REST API. The source code is implemented using Spring Boot and can be found on my Github project.


OkHttp, To send a synchronous GET request we need to build a Request Our article A Quick Guide to Post Requests with OkHttp has more examples of POST requests with OkHttp. Network failures can be due to client connectivity problems, server We use cookies to improve your experience with the site. OKHttp and Http & Http/2 client is widely used in android and java applications to create a request to the server. In this post, I am going to explain some most useful feature of OKHttp. OKHttp is the modern way to make and exchange data and media over HTTP network.


A Guide to OkHttp, OkHttp is a third-party library developed by Square for sending and receive However, there is a separate API provided by OkHttp that makes it easier to send and receive network requests, Get a handler that can be used to post to the main thread client. OkHttp v3.5 now includes support for bidirectional web sockets. Add Internet Permission. To Send POST and GET request to server, means to create connection between server and Android Application, we need to give Internet permission to Android Application. Open your Manifest file and below code: 1. <uses-permission android:name="android.permission.INTERNET" />.