Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 25.android網絡編程-get方式提交數據

25.android網絡編程-get方式提交數據

編輯:關於Android編程

public class MainActivity extends Activity {

	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg){
			Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
		}
	};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void click(View v){
    	EditText et_name = (EditText) findViewById(R.id.et_name);
    	EditText et_pass = (EditText) findViewById(R.id.et_pass);
    	
    	String name = et_name.getText().toString();
    	String pass = et_pass.getText().toString();
    	
    	final String path = "http://192.168.0.102/web2/servlet/LoginServlet?name=" + URLEncoder.encode(name) + "&pass=" + pass;
    	
    	Thread t = new Thread(){
    		
    		@Override
    		public void run(){
    	    	try {
    	    		//2.把網址封裝成一個url對象
    				URL url = new URL(path);
    				//3.獲取客戶端和服務器的連接對象,此時還沒建立連接
    				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    				//4.對鏈接對象進行初始化
    				conn.setRequestMethod("GET");
    				//設置連接超時網絡不好或者地址不對
    				conn.setConnectTimeout(5000);
    				//設置讀取超時客戶端讀取不到數據
    				conn.setReadTimeout(5000);
    				//如果狀態碼是200請求成功
    				if(conn.getResponseCode() == 200){
    					//得到服務器響應頭重的流,流中的數據就是客戶端請求的額數據
    					InputStream is = conn.getInputStream();
    					//讀取流裡面的數據
    					String text = Utils.getTextFromStream(is);
    					
    					Message msg = handler.obtainMessage();
    					msg.obj = text;
    					handler.sendMessage(msg);
    				}else{
    					
    				}
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    	};
    	t.start();
    	

    }


 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved