android中的http通信---(3)通过get、post方式传数据给服务器

本文介绍了在Android中如何通过HTTP的GET和POST方法将数据发送到服务器。通过创建MyServlet文件,并在客户端实现类似注册功能,讨论了处理中文乱码的方法,包括在服务器端对字符编码的转换,以及在响应中设置正确的字符集以防止乱码问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http通过get、post方式传参数给服务器

1.先在myeclipse中新建服务器

新建MyServlet文件

<span style="font-size:14px;">package com.base.module;
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;

public class MyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;       
    public MyServlet() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request,response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("G_UserName");
		String age = request.getParameter("G_UserPassword");
		response.setContentType("text/html;charset=utf-8");
		//获得输出流
		PrintWriter out = response.getWriter();
		//打印接收到的数据
		out.println("name=" + new String(name.getBytes("ISO-8859-1"),"utf-8") +"age=" +age);
		System.out.print("name=" +new String(name.getBytes("ISO-8859-1"),"utf-8"));
		System.out.print(" age=" + age);
	}
}</span>
新建jsp文件,里面放置form表单

<span style="font-size:14px;"><%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
  </head>  
  <body>
    	<form action = "/MyWebProject/MyServlet" method = "get">
    		name:<input type= "text" name="name"><br/>
    		age:<input type="text" name ="age"><br/>
    		submit:<input type = "submit" value="submit"><br/>
    		
    	</form>
  </body>
</html></span>
服务器端完成,接下来写客户端程序!

客户端的功能,类似于注册,有文本框输入用户名,密码,点击提交按钮,提交注册信息。

xml文件

<span style="font-size:14px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/rl">
        <TextView
            android:id="@+id/name"
            android:text="name:"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:id="@+id/name_editText"
            android:layout_below="@id/name"
             />
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/rl">
        <TextView

            android:id="@+id/age_textView"
            android:text="age:"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <EditText
            android:layout_below="@id/age_textView"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:id="@+id/age_editText"
            />
    </RelativeLayout>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="register"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_alignParentStart="true" />
</RelativeLayout></span><strong>
</strong>
MainActivity文件:

package com.example.rr;
import android.app.Activity;
import android.os.Handler;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
    private EditText name;
    private EditText age;
    private Button button;
    private Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init(){
        name = (EditText)findViewById(R.id.name_editText);
        age = (EditText)findViewById(R.id.age_editText);
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String URL = "http://192.168.1.107:8080/MyWebProject/MyServlet";
                new HttpConnection(URL,name.getText().toString(),age.getText().toString()).start();

            }
        });
    }
}
HttpConnection文件

package com.example.rr;
import android.os.Handler;

import java.io.BufferedReader;
import java.io.BufferedWriter;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Properties;


/**
 * Created by xiaoyuer on 2015/11/13.
 */
public class HttpConnection extends Thread{
    private String mUrl;
    private Handler mHandler;
    private String name;
    private String age;
    HttpConnection(String Url,String name,String age)
    {
        this.mUrl = Url;
        this.name = name;
        this.age = age;
    }
    private void doGet(){
        //doget方式发送中文信息一定要转码,用encode方法
        try{
            mUrl = mUrl +"?name=" + URLEncoder.encode(name,"utf-8")+"&age=" + age;
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }

        try {
            //构建url对象
            URL httpUrl = new URL(mUrl);
            //通过openConnection方法打开一个HttpURLConnection对象
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            //设置请求超时,访问网页时可能没给我们应答,设置超时等待时间
            conn.setReadTimeout(5000);
            //设置访问请求方式
            conn.setRequestMethod("GET");
            //做一个包装类,封装信息,把输入流(InputStreamReader)转换成字节流(BufferedReader)
            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){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    public void doPost()
    {
        try {
            //得到操作系统的默认配置信息
            Properties property = System.getProperties();
            property.list(System.out);
            //构建url对象
            URL httpUrl = new URL(mUrl);
            //通过openConnection方法打开一个HttpURLConnection对象
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            //设置请求超时,访问网页时可能没给我们应答,设置超时等待时间
            conn.setReadTimeout(5000);
            //设置访问请求方式
            conn.setRequestMethod("POST");
            //获得输出流
            OutputStream out = conn.getOutputStream();
            //post方法发送的数据先封装成实体
            String content = "name=" + name +"&age" + age;
            //通过out.write()方式发送给后台,getBytes()方法将数据转换为字节流
            out.write(content.getBytes());
            //做一个包装类,封装信息,把输入流(InputStreamReader)转换成字节流(BufferedReader)
            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){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    @Override
    public void run()
    {
        doGet();
    }
}
解决乱码问题:

接到客户端发送的数据之后要对字符编码做处理,否则发送客户端发送中文时会产生乱码问题:解决方法:

out.println("name=" + new String(name.getBytes("ISO-8859-1"),"utf-8") +"age=" +age);先通过.getBytes("ISO-8859-1"),方式转换为字节,再通过utf-8格式进行转码
关键代码如下:

String name = request.getParameter("name");
String age = request.getParameter("age");
response.setContentType("text/html;charset=utf-8"); //设置文本类型,否则会出现乱码
//获得输出流
PrintWriter out = response.getWriter();
//打印接收到的数据
out.println("name=" + new String(name.getBytes("ISO-8859-1"),"utf-8") +"age=" +age);    //转码,否则会出现乱码
System.out.print("name=" +new String(name.getBytes("ISO-8859-1"),"utf-8"));
System.out.print(" age=" + age);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值