【发布时间】:2015-10-06 07:12:33
【问题描述】:
我正在尝试使用 asynctask 通过 http post 方法调用 url 链接。如果链接是“http://example.com/broadcast/”,我正在将参数传递给类似我正在添加“name=ravi/age=30/”这样的参数。该操作正在工作,因为获得了输出,但我得到的响应是包含 JSONArray 的 xml 字符串格式。我只想从 xml 字符串中提取 JSONArray 输出。
webResponse output:
<?xml version="1.0"
encoding="utf-8"?>
<string xmlns="https://example.com/statement">
[{"status":"ok","code":"pass"}]</string>
public class HttpPostExample extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_post_example);
Button saveme=(Button)findViewById(R.id.save);
saveme.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
new AsyncCallWS().execute();
}
});
} //oncreate
private class AsyncCallWS extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
String webResponse="";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/going.asmx/broadcast?");
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(5);
nameValuePair.add(new BasicNameValuePair("alpha", "A1B2C3"));
nameValuePair.add(new BasicNameValuePair("type", "IN"));
nameValuePair.add(new BasicNameValuePair("name", "Somnath"));
nameValuePair.add(new BasicNameValuePair("bind", "Hour Glass"));
nameValuePair.add(new BasicNameValuePair("body", "Hundo"));
//Encoding POST data
try{
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
System.out.println(e);
}
//making POST request.
try{
HttpResponse response = httpClient.execute(httpPost);
webResponse = EntityUtils.toString(response.getEntity());
}catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
System.out.println(e);
} catch (IOException e) {
// Log exception
e.printStackTrace();
System.out.println(e);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return webResponse;
}
@Override
protected void onPostExecute(String webResponse) {
Toast.makeText(getApplicationContext(), webResponse, Toast.LENGTH_LONG).show();
}
} // AsyncTask ends
} //activity
【问题讨论】:
标签: android json xml http-post