需求 : 使用post方式向服務器提供手機號,來查詢手機號的歸屬地
思路 :
在網絡上有一個web服務器,專門用來提供手機號的歸屬地信息,
我們要做的就是訪問該服務器,提供手機號,然後獲取服務器發來的響應碼,
從響應碼中解析出需要的歸屬地信息.
1,定義好佈局文件以及權限的添加。
2,在主線程中獲取需要的控件.
3,開啓一個子線程,在子線程中定義好一個URL,使用該URL對象得到一個HttpURLConnection連接對象.
4,給該連接對象設置好請求方式,請求超時時間,讀取超時時間。
5,給該連接設置一個向服務器寫數據的允許,然後開始向服務器寫數據,將手機號信息發送給服務器
6,連接服務器,得到服務器的返回碼,判斷連接成功沒,如果返回碼爲200,則開始獲取服務器發來的數據
7,在主線程中定義一個Handler,並重寫handleMessage方法。
8,在子線程中,將服務端發送來的數據使用sendMessage發送到主線程中去
9, 在主線程中的 handleMessage收到信息後,將該信息顯示在界面上.
即 :
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
必須放在
conn.connect();前面.
否則會報 java.lang.IllegalStateException: Already connected
代碼 :
public class MainActivity extends Activity {
private EditText editText;
private TextView textView;
//7,在主線程中定義一個Handler,並重寫handleMessage方法。
private Handler handler = new Handler(){
public void handleMessage(Message msg) {
//9,在主線程中的 handleMessage收到信息後,將該信息顯示在界面上.
String text = (String) msg.obj;
textView.setText(text);
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//2,在主線程中獲取需要的控件.
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
}
//點擊事件
public void onClick(View v)
{
//獲取輸入框中的手機號碼
final String phone = editText.getText().toString();
final String data = "mobileCode="+phone+"&userID=";
final String url = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
//3,開啓一個子線程,在子線程中定義好一個URL,使用該URL對象得到一個HttpURLConnection連接對象.
new Thread(new Runnable() {
public void run() {
try {
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
//4,給該連接對象設置好請求方式,請求超時時間,讀取超時時間。
conn.setRequestMethod("POST");//依然要大寫
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
//5,給該連接設置一個向服務器寫數據的允許,然後開始向服務器寫數據,將數據發送給服務器
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
out.write(data.getBytes());
//6,連接服務器,得到服務器的返回碼,判斷連接成功沒,如果返回碼爲200,則開始獲取服務器發來的數據
conn.connect();
int responseCode = conn.getResponseCode();
if(responseCode == 200)
{
InputStream is = conn.getInputStream();
//自定義個方法,用來提取出經輸入流發送來的數據
String text = getStringFromInputStream(is);
//8,在子線程中,將服務端發送來的數據使用 handler 發送到主線程中
Message msg = new Message();
msg.obj = text;
handler.sendMessage(msg);
}
out.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
//自定義個方法,用來將傳進來的輸入流中的需要的信息提取出來,再返回去
protected String getStringFromInputStream(InputStream is) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String text = null;
while((text = br.readLine()) != null)
{
sb.append(text+"/r/n");
}
text = sb.toString();
int start = text.indexOf("\">")+2;
int end = text.indexOf("</");
text = text.substring(start, end);
br.close();
return text;
}
}