之前没有探索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()+"";
}
现在,如何使用 执行相同的POST调用OkHttp,这就是我所在的位置:
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方式传递数据,任何帮助将不胜感激。感谢您。