我想確定是否有更好的方式我的下面的代碼,發送數據到服務器的方式下面的工作,但可以更好?另一種方式比AsyncTask發送數據到服務器
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String json = "";
String s_calc=String.valueOf(calc);;
try {
RequestBody formBody = new FormEncodingBuilder()
// .add("tag","login")
.add("likes", "9")
.add("id", id)
.build();
Request request = new Request.Builder()
.url("http://justedhak.com/old-files/singleactivity.php")
.post(formBody)
.build();
Response responses = null;
try {
responses = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
String jsonData = responses.body().string();
JSONObject Jobject = new JSONObject(jsonData);
int success = Jobject.getInt("success");
if (success == 1) {
// this means that the credentials are correct, so create a login session.
JSONArray JAStuff = Jobject.getJSONArray("stuff");
int intStuff = JAStuff.length();
if (intStuff != 0) {
for (int i = 0; i < JAStuff.length(); i++) {
JSONObject JOStuff = JAStuff.getJSONObject(i);
//create a login session.
// session.createLoginSession(name, pass);
}
}
} else {
// return an empty string, onPostExecute will validate the returned value.
return "";
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("MYAPP", "unexpected JSON exception", e);
}
//this return will be reached if the user logs in successfully. So, onPostExecute will validate this value.
return "RegisterActivity success";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// if not empty, this means that the provided credentials were correct. .
if (!result.equals("")) {
finish();
return;
}
//otherwise, show a popup.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SingleObjectActivity.this);
alertDialogBuilder.setMessage("Wrong username or password, Try again please.");
// alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface arg0, int arg1) {
// alertDialog.dismiss();
// }
// });
// alertDialog = alertDialogBuilder.create();
// alertDialog.show();
}
}
使用改造http://square.github.io/retrofit/ –
其類似於okttp的權利? @KenWolf – Moudiz
Retrofit使用OKHttp作爲http客戶端 –