public class AddressActivity extends Activity
{
/** Called when the activity is first created. */
private Button button;
private EditText editText;
private TextView textView;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.phone);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.result);
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
String mobile = editText.getText().toString();
try
{
String s = new MobileHttpService(AddressActivity.this.getResources().getAssets().open("soap.xml")).httpPost(mobile);
textView.setText(s);
}
catch(Exception e)
{
Toast.makeText(AddressActivity.this, "获取失败", 0);
}
}
});
}
}
public class MobileHttpService
{
private InputStream soapInput;
public MobileHttpService(InputStream is)
{
this.soapInput = is;
}
// 访问地址
private String path = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
// post 方式获取数据
public String httpPost(String mobile) throws Exception
{
String strSoap = readSoap();
strSoap = strSoap.replaceAll("\\$mobile", mobile);
byte[] data = strSoap.getBytes();
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST"); // 以post方式
conn.setDoOutput(true); // 设置可以写入数据 这个一定要写
conn.setChunkedStreamingMode(0); //文档建议使用
//设置请求头参数
conn.setRequestProperty("Content-Type",
"application/soap+xml; charset=utf-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.getOutputStream().write(data);
if (conn.getResponseCode() == 200)
{
return parserSoap(conn.getInputStream());
}
return null;
}
/**
* 解析返回的soap数据
*
* @param inputStream
* @throws Exception
*/
private String parserSoap(InputStream is) throws Exception
{
String s = Util.getString(is);
Log.i("result", s);
return s;
}
/**
* 获取soap文件数据
*
* @return
* @throws Exception
*/
private String readSoap() throws Exception
{
String str = Util.getString(this.soapInput);
return str;
}
}
public class Util
{
/**
* 从输入流中读取字符数据
*
* @param is
* @return
* @throws Exception
*/
public static String getString(InputStream is) throws Exception
{
StringBuffer stringbuff = new StringBuffer();
byte[] b = new byte[1024];
int len = 0;
while (-1 != (len = is.read(b, 0, 200)))
{
String tmp = new String(b, 0, len, "UTF-8");
stringbuff.append(tmp);
}
return stringbuff.toString();
}
}
修改了一下
解析xml