【问题标题】:Android OKHTTP Post RequestAndroid OKHTTP 发布请求
【发布时间】:2015-11-08 18:43:50
【问题描述】:

我目前在执行我的发布请求时出错。我尝试按照其他人在其他 stackoverflow 链接上推荐的操作,但它对我不起作用。以下是我的代码:

public void postGames(View v) {
    //Sets the data input by user into variables
    TextView gameName = (TextView) findViewById(R.id.gameName);
    TextView companyName = (TextView) findViewById(R.id.companyName);
    TextView consoleName = (TextView) findViewById(R.id.consoleName);
    final TextView resultMessage = (TextView) findViewById(R.id.postResult);

    //Set up the url
    String gamesUrl = "sampleurl...";

    //Creates the HTTP client and puts the url info in it
    OkHttpClient client = new OkHttpClient();
    RequestBody formBody = new FormEncodingBuilder()
            .add("name", "hello")
            .add("company", "world")
            .add("console", "Blagh")
            .build();
    Request request = new Request.Builder()
            .url(gamesUrl)
            .post(formBody)
            .build();

    //First checks if the network is available
    if (isNetworkAvailable()) {
        //Executes the post request
        try {
            Response response = client.newCall(request).execute();
            if(response.isSuccessful()){
                resultMessage.setText("Post successful...");
            }
        } catch (IOException e) {
            e.printStackTrace();
            resultMessage.setText("Error in executing post request...");
        }

    } else {
        Toast.makeText(this, getString(R.string.network_unavailable_message),
                Toast.LENGTH_LONG).show();
    }
}

它在“Response response = client.newCall(request).execute();”上给出错误线。我在这里做错了什么吗?

【问题讨论】:

  • 你应该发布堆栈跟踪 - 或者至少说明错误是什么......
  • 你不能在同一个线程上同时做网络和设置文本。您的错误可能是主线程错误上的一个微不足道的网络。\

标签: android okhttp


【解决方案1】:

尝试以这种方式实现响应:

final Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
                         @Override
                         public void onFailure(Request request, final I
                                 }
                             });
                         }
                         @Override
                         public void onResponse(final Response response)
                                 throws IOException {
                             }
                         }
                     }

【讨论】:

    【解决方案2】:

    由于你使用的是 OkHttp 的同步方式,所以在 Android 中你必须在 AsyncTask 中使用它。您的应用可能已经获得 NetworkOnMainThreadException。

    如果你不想要AsyncTask,你应该用它的异步方式来实现OkHttp。

    恕我直言,您可以在以下位置找到更多信息

    https://github.com/square/okhttp/wiki/Recipes

    在 SO 上的以下问题有一个很好的答案:

    Using OKHttp, what is the difference between synchronous request in AsyncTask and OKhttp Asynchronous request?

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      • 2016-04-15
      • 2020-07-10
      • 2019-04-12
      • 2014-06-05
      • 2016-06-15
      • 2021-05-13
      相关资源
      最近更新 更多