如何在activity方法中使用类方法中的okhttp库返回响应

时间:2017-03-28 10:53:10

标签: android android-fragments okhttp

我想在okhttp中使用enque进程获得响应,但这里没有得到确切的解决方案是我的代码 活动代码

 OkHttpClient client = new OkHttpClient();
    String mResponse;
    public String getOkHttpRequest(String url) {
        try {

            Request request = new Request.Builder()
                    .url(url)
                    .build();

           client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    mResponse=response.body().string();


                }
            });

            return mResponse;


        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

这是我的okhttp类方法获取响应,我在onResponse方法中获得响应,但它在活动代码中给我null

 CREATE PROCEDURE dbo.InserSubject @ID int, @Name varchar(50), @Gender     varchar(50), @ Height int
    AS
  BEGIN TRY
      INSERT into Subjects Values (1,'Name','John'),(1,'Gender','Male'),  
       (1,'Height',170); 
  END TRY
  BEGIN CATCH
      error_message()
  END CATCH

1 个答案:

答案 0 :(得分:2)

由于回调的异步性质,您在回调执行之前返回mResponse

选项1)使您的请求同步

// Instead of 
client.newCall(request).enqueue( )

// Use 
String body = client.newCall(request).execute( ).body().toString();

选项2)使方法异步并在调用回调时返回

// Instead of 
public String getOkHttpRequest(String url) { }

// Change method to 
public void getOkHttpRequest(String url) { }

// And have your callback continue your logic
client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
               // TODO handle error correctly, instead of try/catch
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mResponse=response.body().string();

                // TODO call method that uses the response values
            }
        });