get 과 post 방식 으로 데 이 터 를 제출 합 니 다.
                                            
 11053 단어  Android
                    
Android 에서 Http 에서 get 요청 을 제출 하려 면 제출 할 데 이 터 를 url 뒤에 연결 해 야 합 니 다.
서버 쪽:
public class LoginServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //     
        String name =  request.getParameter("name");
        String pass =  request.getParameter("pass");
        System.out.println(name + ";" + pass);
        OutputStream os = response.getOutputStream();
        //      ,   
        if("asd".equals(name) && "123".equals(pass)){
            //            ,      
            os.write("    ".getBytes("utf-8"));
        }
        else{
            os.write("    QAQ".getBytes("utf-8"));
        }
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
클 라 이언 트:
    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
        }
    };
    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();
        Thread t = new Thread(){
            //     url  ,       ,       
            String path = "http://10.66.121.5/WebGet/servlet/LoginServlet?name=" + name + "&pass=" + pass;
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    if(conn.getResponseCode() == 200){
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFrom(is);
                        Message msg = handler.obtainMessage();
                        msg.obj = text;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }public class Utils {
    //             
    public static String getTextFrom(InputStream is){
        byte[] b = new byte[1024];
        int len = 0;
        //         ,           ,            
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            while((len = is.read(b)) != -1){
                bos.write(b, 0, len);
            }
            //                   
            String text = new String(bos.toByteArray());
            return text;
        } catch (IOException e) {
            e.printStackTrace();
        }
        //try           
        return null;
    }
}중국 어 를 사용 하려 면 서버 에서 인 코딩 을 수정 해 야 합 니 다. 서버 에서 바이트 배열 을 받 을 때 iso 8859 - 1 의 메타 로 바이트 배열 을 문자열 로 바 꾸 고 브 라 우 저 는 utf - 8 로 바이트 배열 을 문자열 로 바 꾸 기 때문에 name 을 iso 8859 - 1 의 인 코딩 으로 바이트 배열 로 바 꾸 고 utf - 8 의 메타 로 다시 문자열 로 바 꿔 야 합 니 다.이때 name 은 중국어 가 될 수 있 습 니 다.
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //     
        String name =  request.getParameter("name");
        String pass =  request.getParameter("pass");
        name = new String(name.getBytes("iso8859-1"),"utf-8");
        pass = new String(pass.getBytes("iso8859-1"),"utf-8");
        System.out.println(name + ";" + pass);
        OutputStream os = response.getOutputStream();
        //      ,   
        if("  ".equals(name) && "123".equals(pass)){
            os.write("    ".getBytes("utf-8"));
        }
        else{
            os.write("    QAQ".getBytes("utf-8"));
        }
    }            //         url  ,          ,    
            String path = "http://10.66.121.5/WebGet/servlet/LoginServlet?name=" + URLEncoder.encode(name) + "&pass=" + pass;포스트 방식 데이터 제출
Post 방식 데 이 터 는 url 뒤에 붙 어 있 는 것 이 아니 라 요청 한 흐름 에 놓 여 전 달 된 것 입 니 다. 스 트림 을 통 해 서버 에 기록 되 고 응답 헤더 에 두 개의 속성 필드 가 추가 되 었 습 니 다. Content - type (내용 의 유형) 과 Centent - Length (데 이 터 를 제출 하 는 길이) 는 서비스 기 가 데 이 터 를 처리 하 는 데 더욱 편리 합 니 다.
        Thread t = new Thread(){
            //Post     servlet  ,       
            String path = "http://10.66.121.5/WebGet/servlet/LoginServlet";
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    //             
                    String data = "name=" + URLEncoder.encode(name) + "&pass=" + pass;
                    //  post         
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", data.length() + "");
                    //       ,    
                    conn.setDoOutput(true);
                    //     
                    OutputStream os = conn.getOutputStream();
                    //             
                    os.write(data.getBytes());
                    if(conn.getResponseCode() == 200){
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFrom(is);
                        Message msg = handler.obtainMessage();
                        msg.obj = text;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.