公司有个需求,需要在程序启动的时候去请求电信的一个wap网关,获取用户的手机号码,因为之前没有涉及到这块,所以自己就使用了之前普通的http请求方式,结果返回的信息中手机号码字段死活都是null,换了httpClient等各种方式都不可以,后来在网上搜索资料的时候才知道,原来使用普通的http直连的方式是获取不到用户手机号码的,需要设置电信的CTWAP代理才可以,大致代码如下:
- /*
- * 发送获取手机号码的请求
- * */
- public static String sendPhoneNumRequest(String imsi,Context context)throws Exception {
- String result = "";
- String urlStr = "http://xxxxxxxxxxxxxxxx";
- Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress("10.0.0.200",80));//电信CTWAP代理地址是10.0.0.200
- URL url = new URL(urlStr);
- HttpURLConnection conn=(HttpURLConnection) url.openConnection(proxy);
- if (conn == null){
- throw new IOException("URLConnection instance is null");
- }
- conn.setConnectTimeout(30000);//
- conn.setDoOutput(true); // 发送POST请求必须设置允许输出,表示允许对外输出
- conn.setUseCaches(false); // 不使用Cache
- conn.setRequestMethod("GET");
- conn.setRequestProperty("Accept", "*/*");
- conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
- conn.setRequestProperty("Charset", "UTF-8");
- conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
- int responseCode = conn.getResponseCode();
- Log.i("IndexActivity","responseCode is:"+responseCode);
- if(responseCode == 200){
- InputStream stream = conn.getInputStream();
- result = inStream2String(stream);
- }else{
- }
- return result;
- }
核心代码:
- String urlStr = "http://xxxxxxxxxxxxxxxx";
- Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress("10.0.0.200",80));//电信CTWAP代理地址是10.0.0.200
- URL url = new URL(urlStr);
- HttpURLConnection conn=(HttpURLConnection) url.openConnection(proxy);