Android OKHTTP Post请求
我当前在执行post请求时出错。我尝试在其他stackoverflow链接上执行其他人建议的操作,但对我无效。下面是我的代码:Android OKHTTP Post请求,android,okhttp,Android,Okhttp,我当前在执行post请求时出错。我尝试在其他stackoverflow链接上执行其他人建议的操作,但对我无效。下面是我的代码: public void postGames(View v) { //Sets the data input by user into variables TextView gameName = (TextView) findViewById(R.id.gameName); TextView companyName = (TextView) fin
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();”行中给出了错误。这里有什么地方我做错了吗?试着用以下方式实现响应:
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 {
}
}
}
因为您使用的是OkHttp的同步方式,所以在Android中,您必须在AsyncTask中使用它。您的应用程序可能已经获得NetworkOnMainThreadException 如果您不想使用AsyncTask,那么应该使用其异步方式实现OkHttp IMHO,你可以在 下面的问题有一个很好的答案:
希望这有帮助 您应该发布stacktrace-或者至少说明错误是什么…您不能在同一个线程上同时执行网络和设置文本。您的错误可能是一个微不足道的网络主线程错误\