http 的post与get方法 以及处理中文乱码问题

本文将通过部署一个简单的服务器,并从客户端提交数据来学习post与get传递参数的方法,以及如何处理其中产生的中文乱码问题。


1.部署服务器

     使用Java EE IDE(eclipse版本或者Myeclipse都可以)部署一个简单的服务器,首先创建一个Web 项目web,并创建首页面index.jsp,在该页面设置两个参数:name、age:

    <body>里的 页面代码如下:

<form action="MyServlet" method="get">
	   name:<input type="text" name="name"><br>
	   age:<input type="text"  name="age"><br>
	   submit:<input type="submit" value="submit">
	</form>
创建类:MyServlet.java,该类继承自HttpServlet,重写里面的方法doGet:

代码如下:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//重写该方法
				String name=request.getParameter("name");
				String age=request.getParameter("age");
				PrintWriter out=response.getWriter();//获取一个打印流对象  并打印接收过来的信息
				out.pritln("name="+name +" age="+age);
                                System.out.pritln("name"+name);
				System.out.pritln("age"+age);
	}



在服务器中运行该web项目。由于只是简单的Javaee应用,所以u赘述。


2.客户端:

创建布局页面:regist.xml

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


        <LinearLayout
            android:id="@+id/namelayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="name:"/>
            <EditText
                android:layout_width="180dp"
                android:layout_height="wrap_content"
                android:id="@+id/nameEditText"/>
        </LinearLayout>



    <LinearLayout
        android:layout_below="@id/namelayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="age:"/>
        <EditText
            android:layout_width="180dp"
            android:layout_height="wrap_content"
            android:id="@+id/ageEditText"/>
    </LinearLayout>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/submit"
        android:text="submit"
        android:layout_centerInParent="true"/>
</LinearLayout>


创建类:RegistThread.java  代码为:

package com.pss.regietservletdome;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by pss on 2015/12/31.
 */
public class RegistThread extends Thread {

    String murl;
    String mname ;
    String mage;


    public RegistThread(String url,String name,String age){
        this.mname=name;
        this.murl=url;
        this.mage=age;
    }


    private void doGet(){
        //由于get方式是通过URL传参  而url在这里只是地址 所以需要在做处理
        murl=murl+"?name="+mname+"&age="+mage;

        try {
            URL httpUrl=new URL(murl);//获取传入进来的url地址  并捕获解析过程产生的异常
            //使用是Http访问  所以用HttpURLConnection  同理如果使用的是https  则用HttpsURLConnection
            try {
                HttpURLConnection conn= (HttpURLConnection) httpUrl.openConnection();//通过httpUrl开启一个HttpURLConnection对象
                conn.setReadTimeout(5000);//设置显示超市时间为5秒
                conn.setRequestMethod("GET");//设置访问方式
                final StringBuffer sb=new StringBuffer();//创建缓冲对象
                //将一个输入流转换成一个字节流
                BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String str;
                //循环读出流的数据 按行读取 并将数据存入str
                while((str=reader.readLine())!=null){
                    sb.append(str);
                }
                System.out.println("result="+sb.toString());


            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }


    private void doPost(){
        try {
            URL httpUrl=new URL(murl);
            HttpURLConnection conn= null;//通过httpUrl开启一个HttpURLConnection对象
            try {
                conn = (HttpURLConnection) httpUrl.openConnection();
                conn.setReadTimeout(5000);//设置显示超市时间为5秒
                conn.setRequestMethod("POST");//设置访问方式
                OutputStream out=conn.getOutputStream();//获取一个输出流
                String content="name="+mname+"&age="+mage;
                out.write(content.getBytes());//向服务器写入数据

                /*读取服务器返回的数据*/
                BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuffer sb=new StringBuffer();
                String str;
                while((str=reader.readLine())!=null){
                    sb.append(str);
                }
                System.out.print(sb);//打印数据


            } catch (IOException e) {
                e.printStackTrace();
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
      //  doGet();
        doPost();
    }
}


说明:在上面的doGet()方法中,对传过来的url做了处理,这是因为在get传递参数时,参数是随着url一起被传入的,这在表头可以查看到。

 //由于get方式是通过URL传参  而url在这里只是地址 所以需要在做处理
        murl=murl+"?name="+mname+"&age="+mage;

           doPost()方法,对传过来的url是什么就是什么,这也是跟get方法不同之处,post是通过OutputStream来发送的,这样只需将要发送的数据转换成字节即可。

OutputStream out=conn.getOutputStream();//获取一个输出流
                String content="name="+mname+"&age="+mage;
                out.write(content.getBytes());//向服务器写入数据


什么时候用get和post方法:
     1.数据量较小情况下可以使用get方法,一般只能传入几k,

     2.get方法传的数据是随着url一起的,信息会在表头暴露出来,所以在信息量比较大和安全考虑情况下用post。


MainActivity.java类中的代码:

package com.pss.regietservletdome;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    EditText met_Name;
    EditText met_age;
    Button mbt_submit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.regist);

        inti();

        mbt_submit.setOnClickListener(new sumitListenter());

    }

    private void inti() {
        met_Name=(EditText)findViewById(R.id.nameEditText);
        met_age= (EditText) findViewById(R.id.ageEditText);
        mbt_submit= (Button) findViewById(R.id.submit);
    }

    public class sumitListenter implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            String url="http://localhost:8080/web1/MyServlet";
            new RegistThread(url,met_Name.getText().toString(),met_age.getText().toString()).start();

            Toast.makeText(MainActivity.this,"提交成功!",Toast.LENGTH_SHORT).show();
        }
    }

}

需要注意的是,
  String url="http://localhost:8080/web1/MyServlet";

此处的url中的localhost需要转换成你服务器的ip地址,如果实在不懂得你当前的iup地址,可以打开cmd.exe后输入 ipconfig查看。


运行项目,提交数据后会在web项目中的控制台输出刚提交的数据。



3.解决乱码问题:

 1)在web项目运行后,在index.jsp提交中文数据产生的乱码:

      产生乱码的原因:这是因为通过浏览器给后台传数据时,servlet默认的编码是:iso-8859-1

   所以需要做处理:在MyServlet类中的doGet方法中做转码操作:

   

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//重写该方法
				String name=request.getParameter("name");
				String age=request.getParameter("age");//指定返回的文本类型
				PrintWriter out=response.getWriter();//获取一个打印流对象  并打印接收过来的信息
				out.pritln("name="+new String(name.getBytes("iso-8859-1"),"utf-8")+ age="+age);//转码操作
				System.out.pritln("name"+new String(name.getBytes("iso-8859-1"),"utf-8"));
				System.out.pritln("age"+age);
	}

 2)客户端通过get方法传参数时:(如果此时你用的是虚拟机,测试时不能输入中文,可以先给name和age的文本框text输入一个中文字符)

    产生的原因:客户端发送数据时没有进行转码操作,而get发送数据的方法是通过url传入的的,所以只需在url那里转码即可:

   将该行代码:

murl=murl+"?name="+mname+"&age="+mage;

   改为: murl=murl+"?name="+ URLEncoder.encode(mname,"utf-8")+"&age="+mage; 此时需要加入一个try-catch。

try {
            murl=murl+"?name="+ URLEncoder.encode(mname,"utf-8")+"&age="+mage;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
即可.

 3)通过post传参数:

    通过post是不需要转码的,这是因为客户端默认通过post传递数据时默认的编码就是utf-8。

如果无法确定当前的传值编码是什么,可以使用:

Properties properties=System.getProperties();
properties.list(System.out);//打印当前的发送字符编码

进行查看当前的发送的字符编码格式。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值