Post、Get方法向服务器传递参数

Post、Get方法向服务器传递参数

步骤简介

1)、服务器端用JSP和Servlet搭建后台,接收客户端提交的数据。
2)、在客户端新建xml文件和Activity、Thread。

源码分析

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

   <!-- form action="MyServlet"表示这个form是提交给MyServlet处理的。 -->
   <form action="MyServlet" method="post">

    name:<input type="text" name="name"><br> 
    age: <input type="text" name="age"><br>
    Password: <input type="password" name="Password"><br>

    submit:<input type="submit" value="submit"><br>

   </form>

</body>
</html>

服务器端的表单提交界面,我们在客户端就是在模仿这样的界面向服务器提交表单信息。
服务器端的表单提交界面

Myservlet.java

package com.imooc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MyServlet
 */
public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    /*只写一个doPost方法来处理数据,所以在doGet方法里面调用doPost方法*/
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        String Password = request.getParameter("Password");

        //设置响应头文本类型
        //new String (name.getBytes("iso-8859-1"),"utf-8")
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        /*通过new String (name.getBytes("iso-8859-1"),"utf-8")来处理字符串乱码问题*/
        out.println("name="+new String (name.getBytes("iso-8859-1"),"utf-8")+"   age="+age+"  Password="+Password);


        System.out.println("name="+new String (name.getBytes("iso-8859-1"),"utf-8"));
        System.out.println("age="+age);
        System.out.println("Password="+Password);
    }

}

regist.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/name_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:textSize="30sp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:text="name" />

        <EditText
            android:id="@+id/EditText_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="Please Input Your Name!"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/age_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:orientation="horizontal">

        <TextView
            android:id="@+id/age"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="30sp"
            android:layout_weight="3"
            android:text="age" />

        <EditText
            android:id="@+id/EditText_age"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="Please Input Your Age!"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/Password_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/Password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:layout_weight="3"
            android:text="Password" />
        <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="3" android:ems="10" android:inputType="textPassword">
            <requestFocus />
        </EditText>

        <EditText
            android:id="@+id/EditText_Password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:layout_weight="1"
            android:hint="Please Input Password"/>

    </LinearLayout>


    <Button
        android:id="@+id/regist"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Regist" />

</LinearLayout>

客户端的简易布局界面
这里写图片描述

RegistActivity.java

package com.example.http_01;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;

public class RegistActivity extends Activity {
    private EditText name;
    private EditText age;
    private EditText Password;
    private Button   regist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.regist);

        name = (EditText) findViewById(R.id.EditText_name);  
        age = (EditText) findViewById(R.id.EditText_age);
        Password = (EditText) findViewById(R.id.EditText_Password);
        regist = (Button) findViewById(R.id.regist);

        regist.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                //这里的IP是你现在电脑的IP
            String url = "http://192.168.1.165:8080/web/MyServlet";

             new HttpThread1(url,name.getText().toString(),
             age.getText().toString(),Password.getText().toString())
            .start();   
            }
        });
    }

}

HttpThread1.java

package com.example.http_01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.Buffer;
import android.util.Log;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpThread1 extends Thread {

    String url;
    String name;
    String age;
    String Password;

    public HttpThread1(String url,String name,String age,String Password){

        this.url = url;
        this.name = name;
        this.age = age;
        this.Password = Password;

    }

   private void doGet(){

        //因为doGet方法是通过URL来向网页传参的,所以我们要在URL里面处理我们得到的要提交的name、age、password等数据,同时,需要URLEncoder.encode方法来进行转码
        try {
            url=url+"?name="+URLEncoder.encode(name,"utf-8")+"&age="+age+"&Password="+Password;
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            URL httpUrl=new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(5000);
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String str;
            StringBuffer sb = new StringBuffer();
            while((str=reader.readLine())!=null){//一次只读一行,当这一行不为空的时候认为它是有数据的。
                sb.append(str);
            }
            System.out.println("Result="+sb.toString());

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //doPost在http请求的正文内通过Output方法发送数据,数据存贮在content中,使用out.write(content.getBytes());,将信息转化成字节流就好。
     private void doPost(){

         try {
            URL httpUrl = new URL(url);

            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setReadTimeout(5000);
            OutputStream out = conn.getOutputStream();
            String content = "name="+name+"age="+age+"Password="+Password;
            out.write(content.getBytes());

            BufferedReader read = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String str;

            while((str=read.readLine())!=null){
                sb.append(str);
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

     }


    @Override
    public void run() {
    // TODO Auto-generated method stub
        doGet();
        //doPost();
   }
}

注意事项

1)、注意设置RegistActivity.java为首启动项。
2)、注意doPost和doGet方法的区别。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值