android 獲取手機歸屬地

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章