Android開發使用GET方式向伺服器請求和發送資料

來源:互聯網
上載者:User

Android開發使用GET方式向伺服器請求和發送資料
#1.首先先用建立個servlet處理登陸請求

代碼如下。只實現了doGet方法

package com.wzw.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class LoginServlet */public class LoginServlet extends HttpServlet {private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public LoginServlet() {        super();        // TODO Auto-generated constructor stub    }/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String username=request.getParameter("username");String password=request.getParameter("password");if(username.equals("admin")&&password.equals("123456")){response.getWriter().println("success");}else{response.getWriter().println("failed");}}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub}}

#2.在安卓布局檔案中,布局如下,兩個輸入框和按鈕

                    


在按鈕上添加了點擊事件。#3.在main_activity中,實現具體的代碼

package com.wzw.submitdata;import com.wzw.submitdata.utils.NetUtil;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.View;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {private EditText etUsername;private EditText etPassword;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);etUsername = (EditText) findViewById(R.id.et_username);etPassword = (EditText) findViewById(R.id.et_password);}public void doGet(View v){final String username=etUsername.getText().toString();final String password=etPassword.getText().toString();new Thread(new Runnable() {@Overridepublic void run() {//訪問網路要在子線程中實現,使用get取資料final String state=NetUtil.loginOfGet(username, password);//執行在主線程上runOnUiThread(new Runnable() {public void run() {//就是在主線程上操作,彈出結果Toast.makeText(MainActivity.this, state, 0).show();}});}}).start();}}


#4.另外建立一個訪問網路的小工具類

package com.wzw.submitdata.utils;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class NetUtil {/** * 使用GET訪問去訪問網路 * @param username * @param password * @return 伺服器返回的結果 */public static String loginOfGet(String username,String password){HttpURLConnection conn=null;try {String data="username="+username+"&password="+password;URL url=new URL("http://192.168.1.4:8080/AndroidServer/LoginServlet?"+data);conn=(HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(10000);conn.setReadTimeout(5000);conn.connect();int code=conn.getResponseCode();if(code==200){InputStream is=conn.getInputStream();String state=getStringFromInputStream(is);return state;}} catch (Exception e) {e.printStackTrace();}finally{if(conn!=null){conn.disconnect();}}return null;}/** * 根據輸入資料流返回一個字串 * @param is * @return * @throws Exception  */private static String getStringFromInputStream(InputStream is) throws Exception{ByteArrayOutputStream baos=new ByteArrayOutputStream();byte[] buff=new byte[1024];int len=-1;while((len=is.read(buff))!=-1){baos.write(buff, 0, len);}is.close();String html=baos.toString();baos.close();return html;}}


這樣就可以向伺服器請求資料了




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.