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

26.android網絡變成-post方式提交數據

編輯:關於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);
    	
    	final String name = et_name.getText().toString();
    	final String pass = et_pass.getText().toString();
    	
    	final String path = "http://192.168.0.102/web2/servlet/LoginServlet";
    	
    	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("POST");
    				//設置連接超時網絡不好或者地址不對
    				conn.setConnectTimeout(5000);
    				//設置讀取超時客戶端讀取不到數據
    				conn.setReadTimeout(5000);
    				//5需要設置2個參數Content-Type和Content-Length
    				String data = "name" + URLEncoder.encode(name) +"&pass" + pass;
    				conn.setRequestProperty("Content-Type", "");
    				conn.setRequestProperty("Content-Length", data.length() + "");
    				
    				//設置打開輸出流
    				conn.setDoInput(true);
    				//拿到輸出流
    				OutputStream os = conn.getOutputStream();
    				//使用數據流網服務器提交數據
    				os.write(data.getBytes());
    				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