使用httpurlconnection 把数据提交到服务器
get方式提交
1.@Override 2. public void onClick(View arg0) { 3. new Thread(){ 4. public void run() { 5. String username = et_username.getText().toString(); 6. String pwd = et_pwd.getText().toString(); 7. //get方式提交 参数放到url的后面 8. 9. try { 10. //如果提交的参数包含中文 必须先进行url编码 然后在提交到服务端 11. //URLEncoder.encode(要提交的内容,用到的字符集); 12. String tempUrl = path+"?username="+URLEncoder.encode(username, "utf-8")+"&password="+URLEncoder.encode(pwd, "utf-8"); 13. URL url = new URL(tempUrl); 14. HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 15. connection.setRequestMethod("GET"); 16. connection.setConnectTimeout(10000); 17. int code = connection.getResponseCode(); 18. if(code==200){ 19. InputStream inputStream = connection.getInputStream(); 20. String result = Utils.getStringFromStream(inputStream); 21. showToast(result); 22. } 23. } catch (Exception e) { 24. // TODO Auto-generated catch block 25. e.printStackTrace(); 26. } 27. }; 28. }.start();
通过post方式提交参数 需要手动添加请求头 打开输出流 通过输出流把请求体的内容写到服务端
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//告诉服务器,传递的数据长度
connection.setRequestProperty("Content-Length", String.valueOf(params.length())); 1.new Thread(){ 2. public void run() { 3. String username = et_username.getText().toString(); 4. String pwd = et_pwd.getText().toString(); 5. try { 6. //由于传递的内容是urlencoded 参数的中文内容需要进行url编码 7. String params = "username="+URLEncoder.encode(username,"utf-8")+"&password="+URLEncoder.encode(pwd,"utf-8"); 8. URL url = new URL(path); 9. HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 10. connection.setRequestMethod("POST"); 11. connection.setConnectTimeout(10000); 12. //设置跟post请求相关的请求头 13. //告诉服务器 要传递的数据类型 14. connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 15. //告诉服务器,传递的数据长度 16. connection.setRequestProperty("Content-Length", String.valueOf(params.length())); 17. //打开输出流 18. connection.setDoOutput(true); 19. //通过流把请求体写到服务端 20. connection.getOutputStream().write(params.getBytes()); 21. int code = connection.getResponseCode(); 22. if(code==200){ 23. InputStream inputStream = connection.getInputStream(); 24. String rusult = Utils.getStringFromStream(inputStream); 25. showToast(rusult); 26. } 27. } catch (Exception e) { 28. // TODO Auto-generated catch block 29. e.printStackTrace(); 30. } 31. }; 32. }.start();