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

时间:2017-01-15 22:22:35

标签: java android post spinner

我试图将String发送到服务器,但我遇到了问题。

这是我的方法。

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

界面:

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

}

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

这个想法是当您在微调器中选择间隔时,按钮单击应该将time2发送到服务器。

当我运行该应用程序时,我收到此错误:java.lang.IllegalStateException: Could not execute method for android:onClick

我的问题是如何修复此错误,如果您可以查看发布方法,我也不确定它是否有效。

布局:

<?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>

2 个答案:

答案 0 :(得分:1)

从错误中得到消息“@Field参数只能与表单编码一起使用。”

这意味着,您需要在界面上放置@FormUrlEncoded

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

错误“由:android.os.NetworkOnMainThreadException引起”意味着您的网络进程在主线程中太长,因为您没有使用异步方法。 尝试改变

  call.execute();

使用enqueue方法

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

答案 1 :(得分:0)

您在主线程上执行改进请求。尝试使用AsyncTaskRxAndroidVolley

您也可以尝试这个答案:Does Retrofit make network calls on main thread?

修改即可。例如:

<ice:panelGroup>
    <fieldset>
        <legend>Downstream info</legend>
        <ice:panelGrid columns="2">
            <ice:outputLabel value="Channel type" />
            <ice:outputText value="Primary"/>

            <!-- Downstream -->
            <ice:outputLabel value="Channel ID" />
            <ice:panelSeries id="dsChannelId" value="#{viewCustomerBean.pollModemResult.downstreamChannelID}" var="item">
                <ice:panelGroup style="width:63px;float:left;text-align:center;"><ice:outputText value="#{item}" /></ice:panelGroup>
            </ice:panelSeries>              

            <ice:outputLabel value="Frekvens (Hz)" />
            <ice:panelSeries id="dsFrekvensId" value="#{viewCustomerBean.pollModemResult.downstreamFrekvens}" var="item">
                <ice:panelGroup style="width:63px;float:left;text-align:right;"><ice:outputText value="#{item}" rendered="#{item!=0}"/></ice:panelGroup>
                <ace:linkButton id="FrekID" value="#{item}" action="#{viewCustomerBean.pollModemResult.showFreqPopup}" rendered="#{item==0}"/>
            </ice:panelSeries>              

            <ice:outputLabel value="Received power level  (dBuV)" />
            <ice:panelSeries id="dsPowerId" value="#{viewCustomerBean.pollModemResult.downstreamReceivedPowerLevel}" var="item">
                <ice:panelGroup style="width:63px;float:left;text-align:center;"><ice:outputText value="#{item}" /></ice:panelGroup>
            </ice:panelSeries>              

            <ice:outputLabel value="Downstream SNR  (dB)" />
            <ice:panelSeries id="dsSNRId" value="#{viewCustomerBean.pollModemResult.downstreamSNR}" var="item">
                <ice:panelGroup style="width:63px;float:left;text-align:center;"><ice:outputText value="#{item}" /></ice:panelGroup>
            </ice:panelSeries>              

            <ice:outputLabel value="Downstream MER  (dB)" />
            <ice:panelSeries id="dsMERId" value="#{viewCustomerBean.pollModemResult.downstreamMER}" var="item">
                <ice:panelGroup style="width:63px;float:left;text-align:center;"><ice:outputText value="#{item}" /></ice:panelGroup>
            </ice:panelSeries>              

        </ice:panelGrid>
    </fieldset>
</ice:panelGroup>