手机注册获取验证码的时候,总是说验证码过期,明明刚获取的验证码,还是提示验证码过期。这种情况就是多次网络请求不在同一个Session,很可能就是用了不同的请求方法造成的(eg:httpUrlConnection和httpCilent的get请求或者post请求,建议这种情况就用同一种请求方法的post请求)
关于多次网络请求不在同一个Session(会话)的原因:每次请求的方法不同(例如:分别使用httpclient和httpUrlConnecttion等不同的网络请求方法)
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
简单封装post请求
public static String httpPost(final String url,
final List<NameValuePair> list_params) {
try {
// 得到HttpPost对象
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(list_params,
HTTP.UTF_8));
// 客户端使用POST方式执行请求,获得服务器端的回应response
HttpResponse respone = httpClient.execute(httpPost);
// 判断是否请求成功
if (respone.getStatusLine().getStatusCode() == 200) {
// 获取输入流
InputStream inStream = respone.getEntity().getContent();
int len;
byte b[] = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inStream.read(b)) != -1) {
bos.write(b, 0, len);
}
str = bos.toString();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
调用
List<NameValuePair> list_params = new ArrayList<NameValuePair>();
list_params.add(new BasicNameValuePair("uname", "xiaomeng"));
list_params.add(new BasicNameValuePair("loginPassword", "123456"));
String response = HttpUtils.httpPost(url, list_params);