使用Okhttp无法连接到Web服务

时间:2018-07-20 15:40:17

标签: android web-services http okhttp

我正在构建一个调用Web服务的应用程序。当我使用HttpUrlConnection类向Web服务发出请求时,它可以工作,但是我替换为OkHttpClient进行请求,则我的应用无法连接到服务,OnFailure方法是始终以以下内容调用:"OnFailure: failed to connect to todolistmobileapp-env.ap-south-1.elasticbeanstalk.com/13.232.26.212 (port 80) after 4ms"

有人告诉我我遇到什么问题吗?

public class RequestRegisterAuthor extends AppNetworkRequest {

    public static final String TAG = RequestRegisterAuthor.class.getSimpleName();

    private final String url = ToDoRestAPIs.baseRemoteHostUrl  + ToDoRestAPIs.registerAuthor;

    public RequestRegisterAuthor(APICallbackListener apiCallbackListener, Object jsonRequestBody){
        super(apiCallbackListener);
        request = new Request.Builder().url(url)
                .addHeader(AppNetworkRequest.CONTENT_TYPE, AppNetworkRequest.JSON_CONTENT_TYPE)
                .post(RequestBody.create(MediaType.parse(JSON_CONTENT_TYPE), jsonRequestBody.toString()))
                .build();
    }

    @Override
    public void makeBackEndRequest() {
        new Thread(this).start();
    }

    @Override
    public void run() {
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call,final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        apiCallbackListener.onFailureCallback(e.getMessage());
                        Log.e(TAG + "- OnFailure", e.getMessage());
                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if(response.code() == 201){
                        responseObject = new GsonBuilder().create().fromJson(response.body().string(), Author.class);
                    }
                    else{
                        responseObject = new Error(response.code(), response.message());
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                    responseObject = new Error(101, e.getMessage()); // pre-defined code.
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        apiCallbackListener.onSuccessCallback(REQUEST_TYPE.REQUEST_REGISTER_AUTHOR, responseObject);
                    }
                });
            }
        });
    } }

这是logcat:

https://pastebin.com/3CNsGrPm

1 个答案:

答案 0 :(得分:0)

我相信HttpUrlConnection在幕后使用OkHttp,您能为两种连接方法发布代码吗?