当我单击保存按钮时,它将使用参数flexid执行后台PATCH任务:
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String loc = flexlocationid.getText().toString().trim();
Utils.log("loc: " + loc);
SendfeedbackPatch jobpatch = new SendfeedbackPatch();
jobpatch.execute(loc);
}
});
后台任务是:
private class SendfeedbackPatch extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "UserPreferedLocation";
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
@Override
protected String doInBackground(String... params) {
String flexid = params[0];
Utils.log("flexid: " + flexid);
final String url_patch_prefered_location = Constant.URI_BASE_FLEX;
String contentType;
contentType = "application/x-www-form-urlencoded";
HttpClient httpClient = new DefaultHttpClient();
HttpPatch httpPatch= new HttpPatch(url_patch_prefered_location);
httpPatch.setHeader("Content-Type", contentType);
httpPatch.setHeader("Authorization", "Bearer " + token);
httpPatch.setHeader("Accept", "application/json");
httpPatch.setHeader("Accept-Charset", "utf-8");
// do above Server call here
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("flex_id", flexid));
try
{
HttpResponse response = httpClient.execute(httpPatch);
HttpEntity entity = response.getEntity();
if (entity != null) {
// EntityUtils to get the reponse content
String content = EntityUtils.toString(entity);
Utils.log("daftar content: " + content);
JSONObject hasiljson = new JSONObject(content);
Utils.log("hasiljson object: " + hasiljson);
String success = hasiljson.getString("success");
Utils.log("success: " + success);
}
// writing response to log
Log.d("Http Response:", response.toString());
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
@Override
protected void onPostExecute(String message) {
//process message
Toast.makeText(context,
"Prefered training location updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, home.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
finish();
}
}
我使用log Utils.log(“ flexid:” + flexid);获得了flexid,当我登录Utils.log(“ daftar content:” + content);时发现了问题,它返回:daftar content:{“ errors”: {“ flex_id”:[“ flex id字段为必填。”]}},这表示flex_id填充得不好。如何更正flex_id是否正确填充(补丁)?
最佳答案
这里:
content: {"errors":{"flex_id":["The flex id field is required."]}}
因为使用
BasicNameValuePair
创建了flex_id
,但未通过调用setEntity
的HttpPatch
方法在HTTP请求中进行设置。这样做:....
httpPatch.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPatch);
...