在改造2.0中,Alaways进入失败状态

时间:2017-09-12 10:31:25

标签: retrofit2

我想点击api:www.xyz.com/abc_cc/cc/userregister/newuser

这是我的代码:

    public class MainActivity extends AppCompatActivity {


    public static final String BASE_URL = "abc.com/abc_cc/cc/";

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

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
.client(getUnsafeOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Endpoints endpoints= retrofit.create(Endpoints.class);
        endpoints.newuser("{\"full_name\":\"sss\",\"states_id\":\"20\",\"mobile\":\"9876543210\",\"password\":\"******\",\"accept_terms\":true,\"Userid\":\"0\",\"refer\":\"\",\"ip-address\":\"1.2.3.4\",\"device_type\":\"samsung J5\",\"os-version\":\"5.0.1\",\"client\":\"app\",\"secret_key\":\"44\"}")
                .enqueue(new retrofit2.Callback<Items>() {
                    @Override
                    public void onResponse(retrofit2.Call<Items> call, retrofit2.Response<Items> response) {
                        System.out.println("onResponse : "+response.message());
                        System.out.println("onResponse : "+response.body());
                        System.out.println("onResponse : "+response.code());
                        System.out.println("onResponse : "+response.errorBody());
                        System.out.println("onResponse : "+response.isSuccessful());
                        System.out.println("onResponse : "+response.raw());
                        System.out.println("onResponse : "+response);
                    }

                    @Override
                    public void onFailure(retrofit2.Call<Items> call, Throwable t) {
                        System.out.println("onFailure"+call);

                    }
                });


    }

    public static OkHttpClient getUnsafeOkHttpClient() {

        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] chain,
                        String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] chain,
                        String authType) throws CertificateException {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[0];
                }
            } };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts,
                    new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext
                    .getSocketFactory();

            OkHttpClient okHttpClient = new OkHttpClient();
            okHttpClient = okHttpClient.newBuilder()
                    .sslSocketFactory(sslSocketFactory)
                    .hostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();

            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}

界面:

public interface Endpoints {
    @POST("/userregister/newuser")
    @FormUrlEncoded
    Call<Items> newuser(@Field("Data") String Data);

}

POJO课程:

public class Items {
    @SerializedName("Response-Status")
    @Expose
    private Boolean responseStatus;
    @SerializedName("Response-Validate")
    @Expose
    private Boolean responseValidate;
    @SerializedName("Response-Message")
    @Expose
    private String responseMessage;
    @SerializedName("Response-Data")
    @Expose
    private ResponseData responseData;

    public Boolean getResponseStatus() {
        return responseStatus;
    }

    public void setResponseStatus(Boolean responseStatus) {
        this.responseStatus = responseStatus;
    }

    public Boolean getResponseValidate() {
        return responseValidate;
    }

    public void setResponseValidate(Boolean responseValidate) {
        this.responseValidate = responseValidate;
    }

    public String getResponseMessage() {
        return responseMessage;
    }

    public void setResponseMessage(String responseMessage) {
        this.responseMessage = responseMessage;
    }

    public ResponseData getResponseData() {
        return responseData;
    }

    public void setResponseData(ResponseData responseData) {
        this.responseData = responseData;
    }

}

我收到了这个回复:

{protocol=http/1.1, code=404, message=Not Found, url=www.xyz.com/userregister/newuser}

我已经给出了正确的网址,那为什么它只占了一半呢?

我试过https://code.tutsplus.com/tutorials/sending-data-with-retrofit-2-http-client-for-android--cms-27845的例子。此示例和示例中给出的链接工作正常,但如果我对我的网址执行相同操作,则会出现上述错误

3 个答案:

答案 0 :(得分:2)

我希望检查您的解析问题是否可能发生。

Exception calling "LoadFrom" with "1" argument(s): "Could not load file or assembly 'file:///F:\Qubit 
 Systems\ShipperBuyerV1\module-zero-template-2.1.1\src\packages\EntityFramework.6.1.3\tools\EntityFramework.PowerShell.Utility.dll' or one of its dependencies. Operation is not supported. 
    (Exception from HRESULT: 0x80131515)"
 At F:\Qubit Systems\ShipperBuyerV1\module-zero-template-2.1.1\src\packages\EntityFramework.6.1.3\tools\EntityFramework.psm1:780 char:5
+     $utilityAssembly = [System.Reflection.Assembly]::LoadFrom((Join-P ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileLoadException

 You cannot call a method on a null-valued expression.
  At F:\Qubit Systems\ShipperBuyerV1\module-zero-template-2.1.1\src\packages\EntityFramework.6.1.3\tools\EntityFramework.psm1:781 char:5
 +     $dispatcher = $utilityAssembly.CreateInstance(
 +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

 Exception calling "CreateInstanceFrom" with "8" argument(s): "Could not load file or assembly 'file:///F:\Qubit 
   Systems\ShipperBuyerV1\module-zero-template-2.1.1\src\packages\EntityFramework.6.1.3\tools\EntityFramework.PowerShell.dll' or one of its dependencies. Operation is not supported. (Exception 
 from HRESULT: 0x80131515)"
    At F:\Qubit Systems\ShipperBuyerV1\module-zero-template-2.1.1\src\packages\EntityFramework.6.1.3\tools\EntityFramework.psm1:809 char:5
 +     $domain.CreateInstanceFrom(
 +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileLoadException

//添加这个lije你有例外。

 @Override
public void onFailure(retrofit2.Call<Items> call, Throwable t) {
 System.out.println("onFailure"+call);

答案 1 :(得分:0)

为此更改Endpoints界面:

public interface Endpoints {
    @POST("userregister/newuser")
    @FormUrlEncoded
    Call<Items> newuser(@Field("Data") String Data);

}

请注意,我删除了尾部斜杠/。这样,Retrofit会将您定义的路径附加到BASE_URL。

答案 2 :(得分:0)

请参阅docs for Retrofit.Builder以获取更详细的解释,但要特别注意这些位:

  

基本网址应始终以/.

结尾      

尾随/确保端点值是相对路径   将正确地附加到具有路径组件的基础。

     

...

     

包含前导/是绝对值的端点值。

     

绝对值仅保留baseUrl中的主机并忽略any   指定的路径组件。

如前所述,您对Endpoints.newuser()的调用中引用的路径是绝对路径,因此基本URL中主机之后的路径段将被删除(因为这是记录的行为)。

因此,您应该更改Endpoints接口以改为使用相对路径,如下所示:

    public interface Endpoints {
        @POST("userregister/newuser")
        @FormUrlEncoded
        Call<Items> newuser(@Field("Data") String Data);
    }