我正在创建一个 android webservice 客户端(restful web 服务)。我试图从 web 服务中读取一个简单的值,但是在我的应用程序中,我无法从 web 服务 xml 文件中提取数据值。
从 web 服务返回的数据如下所示:
在我的应用程序中,数据如下所示:
我只需要读出值而不是整个 xml 文件。有什么想法我该怎么做?
这是我的代码:
MainActivity.java
package com.hit.resttest;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
@Override
public void onClick(View arg0)
{
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String>
{
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException
{
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(beer);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
@Override
protected String doInBackground(Void... params)
{
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.118:8080/WebService/random");
String text = null;
try
{
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
}
catch (Exception e)
{
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results)
{
if (results!=null)
{
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}