简体   繁体   English

使用 Retrofit 2 的 Android 中的 HTTP POST 请求

[英]HTTP POST request in Android using Retrofit 2

I'm trying to send String to the server, but I'm having problems with it.我正在尝试将 String 发送到服务器,但我遇到了问题。

This is my method.这是我的方法。

ppublic void intervalPost(View view) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://requestb.in/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        PostInterface service = retrofit.create(PostInterface.class);
        Call<ResponseBody> call = service.postTime(time2);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d("Postavke", "Reached onResponse");
                if (!response.isSuccess()) {
                    Log.d("Postavke", "No Success");
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call,Throwable t) {
                // Toast for the moment
                // Appropriate error handling code should be present here
                Toast.makeText(Postavke.this, "Failed !", Toast.LENGTH_LONG).show();
            }
        });
}

And interface:和界面:

public interface PostInterface {
@FormUrlEncoded
@POST("/1b2bqxl1")
Call<ResponseBody> postTime(@Field("interval") String time);

} }

I'm getting string time2 from spinner:我从微调器获取字符串 time2:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String label = spinner.getSelectedItem().toString();
            tokens = new StringTokenizer(label, " ");
            time = tokens.nextToken().trim();
            timeConvert = Integer.parseInt(time);
            if (timeConvert == 1 || timeConvert == 2 || timeConvert == 3 || timeConvert == 6 || timeConvert == 12)
                timeConvert = timeConvert * 60;
            time2 = String.valueOf(timeConvert);
        }

The idea is when you chose interval in spinner, button click should send time2 to server.这个想法是当你在微调器中选择间隔时,按钮点击应该将 time2 发送到服务器。

When I run the application I'm getting this error: java.lang.IllegalStateException: Could not execute method for android:onClick当我运行应用程序时,我收到此错误: java.lang.IllegalStateException: Could not execute method for android:onClick

My question is how to fix this error and also if you could check post method, I'm not sure if it'll work.我的问题是如何修复这个错误,如果你可以检查 post 方法,我不确定它是否会起作用。

Layout:布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
android:orientation="vertical"
>


<TextView
    android:text="@string/odaberi_interval"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/odabirintervala"
    android:textSize="20sp"
    android:layout_marginTop="30dp"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="20dp"
    android:textColor="#148299"
    />

<Spinner
    android:id="@+id/spinner"
    android:layout_width="125dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="33dp"
    android:layout_toRightOf="@id/odabirintervala"
    android:drawSelectorOnTop="true"
    ></Spinner>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Promijeni interval"
    android:layout_below="@id/spinner"
    android:layout_marginTop="20dp"
    android:layout_centerHorizontal="true"
    android:onClick="intervalPost"
    android:id="@+id/intervalButton"
    />
</RelativeLayout>

From the error you get the message "@Field parameters can only be used with form encoding."从错误中您会收到消息“@Field 参数只能与表单编码一起使用。”

It means, you need to put @FormUrlEncoded on your interface这意味着,您需要将 @FormUrlEncoded 放在您的界面上

@FormUrlEncoded
@POST("/1gics1o1")
Call<Response> postTime(@Field("interval") String time);

The error "Caused by: android.os.NetworkOnMainThreadException" means your network process is too long being in the main thread, because you are not using asynchronous method.错误“Caused by: android.os.NetworkOnMainThreadException”表示您的网络进程在主线程中的时间过长,因为您没有使用异步方法。 Try to change尝试改变

  call.execute();

with enqueue method使用入队方法

  call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.d("Postavke", "Reached onResponse");
            if (!response.isSuccess()) {
                Log.d("Postavke", "No Success");
            }else{
                Log.d("Postavke", "responsebody  => "+ response.body().toString());
            }


        }

        @Override
        public void onFailure(Call<ResponseBody> call,Throwable t) {
            // Toast for the moment
            // Appropriate error handling code should be present here
            Toast.makeText(Postavke.this, "Failed !", Toast.LENGTH_LONG).show();
        }
    });

You do retrofit request on main thread.您在主线程上进行改造请求。 Try to use AsyncTask or RxAndroid or Volley .尝试使用AsyncTaskRxAndroidVolley

Also you can try this answer: Does Retrofit make network calls on main thread?你也可以试试这个答案: Retrofit 在主线程上进行网络调用吗?

Edit .编辑 Example:例子:

public void intervalPost(View view) {
  try {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://requestb.in/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    PostInterface service = retrofit
      .create(PostInterface.class);
      .postTime(time2)
      .enqueue(new Callback<Response>() {
                @Override
                public void onResponse(Call<Response> call, Response<Response> response) {
                  // code here
                }

                @Override
                public void onFailure(Call<Response> call, Throwable t) {
                  // code here
                }
            });
  } catch (IOException Ex) {
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM