使用OKHTTP3将POST请求发送到Web服务器

时间:2018-10-29 09:58:13

标签: android

我正在创建用于电费支付的应用程序。我希望应用程序像这样工作。客户输入他/她的电表编号以及要支付的金额。单击提交按钮后,必须通过POST请求通过OKHTTP3协议将该信息发送到服务提供商。我写了下面的代码,当我单击“提交”按钮时,它什么也不显示。请帮忙。

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

}

5 个答案:

答案 0 :(得分:1)

我将为您提供一个解决方案,以及有关如何总体上使用OKHTTP3 POST请求的一般说明,因为将来您可能还需要扩展项目。

  • 第一步,您需要将要发送的数据转换为JSON对象。这将使您的代码更干净,更可维护。为此,请为您需要发送的数据创建一个Java类。在您的情况下,java类将如下所示:

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

然后,将以下行添加到模块的build.gradle中:

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

这允许您使用gson库将Java对象自动转换为JSON对象。

然后创建JSON对象,其中将包含您要发送的数据。这样做如下:

    Data data=new 
      Data(txtinputmeter.getText.toString(),txtinputamount.getText.toString());
      Gson gson = new GsonBuilder().serializeNulls().create();
       String JSONObjectString = gson.toJson(data);
  • 第二步,如下创建OKHTTP Post方法:

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

上述方法允许您将消息发送到服务器,并在服务器具有正文的情况下从服务器接收响应。

  • 第三步,发送包含您的数据的JSON对象 这样做如下:

    doPostOkHttp("your URL", JSONObjectString );
    

然后监视您的logcat并查看服务器响应的样子。


在单独的线程中运行doPostOkHttp是一个好习惯。只要您了解上述代码,就可以轻松地使用代码中使用的回调技术。

如果仍然遇到问题,请逐步完成此非常简单的教程,以便您了解有关如何在OKHTTP中使用Post的所有信息: http://www.vogella.com/tutorials/JavaLibrary-OkHttp/article.html

答案 1 :(得分:0)

发送请求后,您正在显示新的活动。因此,当前的Activity无法检索服务器响应...您必须在收到响应后放入Submit()方法。

答案 2 :(得分:0)

根据您的编码,您正在导航至响应之前的 Payzesa.class

因此将意图或动作放在其中

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

答案 3 :(得分:0)

将以下功能用于OKHTTP3中的POST调用

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

}

答案 4 :(得分:0)

您可以将Retrofit与OkHttp3配合使用。

首先,您需要创建OkHttp客户端。

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

使用OkHttp客户端构建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();

接下来,您必须创建一个包含RESTapi方法的接口

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

RESTApi restApi = retrofit.create(RESTApi.class);