以前没有探索过OkHttp
,使用AsyncTask
的网络调用目前工作正常,但想切换到OkHttp
以满足其他要求,
以下是我如何使用AsyncTask
进行网络调用:
private class HTTPAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
try {
return HttpPost(urls[0]);
} catch(Exception e) {
e.printStackTrace();
return "Error!";
}
} catch (Exception e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Log.d("data is being sent",result);
}
}
private String HttpPost(String myUrl) throws IOException {
String result = "";
URL url = new URL(myUrl);
// 1. create HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(StringData);
writer.flush();
writer.close();
os.close();
// 4. make POST request to the given URL
conn.connect();
// 5. return response message
return conn.getResponseMessage()+"";
}
现在,如何与OkHttp
执行相同的POST
调用,这是我所在的地方:
private void makeNetworkCall()
{
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url(post_url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e)
{
Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.e("TAG","SUCCESS");
}
});
}
但是,不确定如何使用OkHttp
方式传递数据,任何帮助将不胜感激。谢谢你。
老实说,我什至不会打扰普通的 OkHttp Retrofit 是您选择的工具,它非常通用(甚至支持类似 Rx 的样式(,并减轻了您现在必须处理的许多低级内容。
为了进一步提高您的技能,请查看此内容
我同意答案,因为如果您计划对后端进行许多不同的网络调用,从长远来看,Retrofit 可能会更好。但是如果你坚持在较低级别使用 OkHttp,那么你可以做这样的事情:
String jsonString = json.toString();
RequestBody body = RequestBody.create(JSON, jsonString);
Request request = new Request.Builder()
.header("Content-Type", "application/json; charset=utf-8")
.url(post_url)
.post(body)
.build();
client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
@Override
public void onFailure(Request request, IOException throwable) {
}
@Override
public void onResponse(Response response) throws IOException {
}
});