Android OKHTTP发布请求

时间:2015-11-08 18:43:50

标签: android okhttp

我目前在执行帖子请求时遇到错误。我尝试做其他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();
    }
}

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

2 个答案:

答案 0 :(得分: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 {
                             }
                         }
                     }

答案 1 :(得分:0)

由于您使用的是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?

希望这有帮助!

相关问题