android get联网

来源:互联网 发布:广州淘宝运营工资 编辑:程序博客网 时间:2024/06/06 13:06

public class MainActivity extends Activity {
 // GET发送方式
 Button getButton = null;

 TextView tv = null;
 // 输入框
 EditText inputEdit = null;
 // 服务端返回状态
 final int REPONSE_OK = 200;
 final String GET_URL = "http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=";

 private boolean isPressed = false;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  initView();
 }

 /**
  * 描述:初始化View
  * */
 final void initView() {
  tv = (TextView) findViewById(R.id.showM);
  inputEdit = (EditText) findViewById(R.id.inputQQ);
  getButton = (Button) findViewById(R.id.getB);
  getButton.setOnClickListener(clickDeal);

 }

 /**
  * 事件处理
  * */
 View.OnClickListener clickDeal = new View.OnClickListener() {

  public void onClick(View v) {
   if (v == getButton) {
    if (!isPressed) {
     isPressed = true;
     doGet();
    }
   }
  }
 };

 /**
  * 用Get方式联网
  * */
 private final void doGet() {
  HttpGet get = null; // 用get方式联网
  HttpResponse response = null;// 等待应答
  try {
   if (inputEdit != null && inputEdit.getText().toString().length() > 0) {
    String QQ = inputEdit.getText().toString();
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);
    HttpClient httpClient = new DefaultHttpClient(httpParams);

    get = new HttpGet(GET_URL + QQ);

    response = httpClient.execute(get);
    if (response.getStatusLine().getStatusCode() == REPONSE_OK) {
     byte[] b = EntityUtils.toByteArray(response.getEntity());
     String isLogin = new String(b, "utf-8");
     String t_isLogin = splitStr(isLogin, ">",  1);
     tv.setText("GET:" + t_isLogin);
     tv.invalidate();
    }
    isPressed = false;
   }
  } catch (Exception e) {
   isPressed = false;
   e.printStackTrace();
  } finally {
   if (get != null) {
    get.abort();
   }
  }
 }

 /**
  * 描述:截取字符串
  * */
 final String splitStr(String _str, String which, int count) {
  // 获得String对象内子字符串开始的位置
  int firstStr = _str.indexOf(which);
  int t_start = _str.indexOf(which, firstStr + 1);
  String result = _str.substring(t_start + 1, t_start + 1 + count);
  String strResult = "";

  if (result.toLowerCase().equals("y")) {
   strResult = "此QQ号在线!";
  } else if (result.toLowerCase().equals("n")) {
   strResult = "此QQ号不在线或隐身!";
  } else if (result.toLowerCase().equals("e")) {
   strResult = "QQ号码错误!";
  } else {
   strResult = "无法验证!";
  }
  return strResult;

 }

}

//添加权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

原创粉丝点击