需求 : 使用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;
}
}