我正在开发一个应用程序,该应用程序通过添加参数用户名和密码来解析来自 URL 的数据并更新它,解析已完成,但我无法更新或写/发布回服务器。
private class abc extends AsyncTask<String,String,String>{
String response = "";
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
DefaultHttpClient client = new DefaultHttpClient();
HttpPost p1 = new HttpPost("Url");
List<NameValuePair>data = new ArrayList<NameValuePair>(2);
data.add(new BasicNameValuePair("UserName", "abc"));
data.add(new BasicNameValuePair("Password", "def"));
try {
p1.setEntity(new UrlEncodedFormEntity(data));
HttpResponse execute = client.execute(p1);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
try {
JSONObject inf = new JSONObject(result);
int id = inf.getInt("UserID");
String username = inf.getString("UserName");
TextView t1 = (TextView)findViewById(R.id.textView1);
t1.setText("user id :"+id+"\n"+"user name :"+UserName);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPostExecute(result);
}
最佳答案
使用用户名和密码以及 userId 在 doInBackground 中传递您的参数 用户名和密码是您当前的用户名和密码(例如获取edittext值)并使用post方法调用asyntask
关于android - 如何在asynctask中写入解析后的json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29246310/