API调用的无效改装响应

时间:2018-08-12 16:52:30

标签: java android ssl retrofit2 android-network-security-config

我正在尝试使用Retrofit 2从Android登录到服务器。登录的API在邮递员(REST客户端工具)中运行良好,并得到了这样的响应

[
    {
        "success": true,
        "message": "Enjoy your token!",
        "token": "ABCDEFGHIJKLMNOPQESTUVWXYZ",
        "log_id": 1234
    }
]

但是当我使用Retrofit 2在Android中尝试相同的流程时,我得到了不同的输出。当我在android中调用Login API时,这是Android的日志片段。

08-12 11:27:29.299 13457-13593/com.example.user.retrofit D/OkHttp: --> POST http://www.test.com/api/authenticate http/1.1
08-12 11:27:29.300 13457-13593/com.example.user.retrofit D/OkHttp: Content-Type: application/json; charset=UTF-8
    Content-Length: 181
    Accept: application/json
08-12 11:27:29.301 13457-13593/com.example.user.retrofit D/OkHttp: {"data":"VTJGc2RHVmtYMWdNYj1E"}
    --> END POST (181-byte body)
08-12 11:27:35.087 13457-13593/com.example.user.retrofit D/OkHttp: <-- 200  https://www.test.com/api/authenticate (5785ms)
    content-type: text/html
    cache-control: no-cache
    content-length: 210
    x-iinfo: 7-48850495-0 0NNN RT(1534053455965 0) q(0 -1 -1 5) r(0 -1) B10(4,289,0) U5
    set-cookie: visid_incap_1748743=CMWA4MwbTNGL5G0hHnAZBE/Mb1sAAAAAQUIPAAAAAADakNS0YTyMIvKXh6Zh0cjx; expires=Sun, 11 Aug 2019 09:31:38 GMT; path=/; Domain=.test.com
    set-cookie: incap_ses_705_1748743=z9lvBtlqCnHsdSffSqrICU/Mb1sAAAAAgZliHJa2lcppoIp0iVqtng==; path=/; Domain=.test.com
08-12 11:27:35.088 13457-13593/com.example.user.retrofit D/OkHttp: <html>
    <head>
    <META NAME="robots" CONTENT="noindex,nofollow">
    <script src="/_Incapsula_Resource?SWJIYLWA=5074a744e2e3d891814e9a2dace20bd4,719d34d31c8e3a6e6fffd425f7e032f3">
08-12 11:27:35.089 13457-13593/com.example.user.retrofit D/OkHttp: </script>
    <body>
    </body></html>
    <-- END HTTP (210-byte body)

用于登录的Android Activity类如下

package com.example.user.retrofit;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.io.IOException;
import java.security.cert.CertificateException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public class MainActivity extends AppCompatActivity {

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

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.test.com/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(getUnsafeOkHttpClient().build())
                .build();
        LoginRequest login = new LoginRequest();
        login.setData("VTJGc2RHVmtYMWdNYj1E");
        GitHubService service = retrofit.create(GitHubService.class);
        service.login(login).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    Log.d("OnResponse", response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("OnFailure", "Failed", t);
            }
        });

    }
    public static OkHttpClient.Builder 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[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            // add logging as last interceptor
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logging);  // <-- this is the important line!
            return builder;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public interface GitHubService {
        @Headers({
                "Accept: application/json"
        })
        @POST("authenticate")
        Call<ResponseBody> login(@Body LoginRequest user);
    }

    private static class LoginRequest {
        private String data;


        public String getData() {
            return data;
        }

        public void setData(String data) {
            this.data = data;
        }
    }
}

请任何人都可以告诉我,为什么我在Android上尝试获取HTML内容。要获得正确的JSON响应需要做什么?

2 个答案:

答案 0 :(得分:0)

发送User-Agent:“您的应用名称”标题正文也

答案 1 :(得分:0)

谢谢您提出这个问题,此问题与服务器端框架(如laravel php)有关,该框架可保护未经授权的访问并防止出现未知的客户端请求(在您的情况下,您的改进是客户端)。它会检查“ User-Agent”标头值,如果未提供,则会抛出“验证码错误”。当您避免服务器发送的“会话cookie”时,也会发生这种情况。浏览器可以非常轻松地处理和维护会话cookie,但改型似乎在默认情况下维护会话Cookie时遇到问题。

1。将新的拦截器添加到您的okhttpClientBuilder

.loader {
position: fixed;
right: 2%;
bottom: 0%;
width: 15vmin;
visibility: hidden;
}

2。在您的android studio-> build.gradle文件(项目级别)中,在build.gradle文件中找到以下类似结构,并添加如下所示的Maven存储库

okhttpClientBuilder.addInterceptor(new Interceptor(){
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Response response;
                Request request = original.newBuilder()
                        .addHeader("User-Agent", System.getProperty("http.agent"))//important
                        .addHeader("Accept", "application/json")                      
                        .method(original.method(), original.body())
                        .build();
                request.headers().getAll("Cookie"));
                response= chain.proceed(request);
                response.headers().getAll("Set-Cookie"));
                return  response;
          }
     });

3。在build.gradle文件(应用程序级别)中添加依赖项

 allprojects {
    repositories {
    //other configs.....

    //add this if not present
    maven { url "https://jitpack.io" } 
     }
  }
  1. 同步您的项目

  2. 在创建okhttpClientBuilder后添加以下代码

    dependencies { //other important dependency.... //add this dependency for handling cookies implementation 'com.github.franmontiel:PersistentCookieJar:v1.0.1' }