前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >通过GET方式传递数据给服务器

通过GET方式传递数据给服务器

作者头像
提莫队长
发布2019-02-21 15:54:12
1.1K0
发布2019-02-21 15:54:12
举报
文章被收录于专栏:刘晓杰刘晓杰刘晓杰

1.web服务端的建立

建立Dynamic Web Project,名称为ServerGET

2.新建servlet

这里写图片描述
这里写图片描述

自动生成的ServerGET.java中有 @WebServlet(“/ServerGET”) 所以web.xml就不需要配置了

3.编写ServerGET.java

package com.example.servletGet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ServerGET
 */
@WebServlet("/ServerGET")
public class ServerGET extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServerGET() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        System.out.println(name + "   " + age);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }
}

4.测试服务端

这里写图片描述
这里写图片描述

5.建立android客户端

布局文件main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.userinformation.MainActivity" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="name:" />

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="age:" />

    <EditText
        android:id="@+id/age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="save" />

</LinearLayout>
这里写图片描述
这里写图片描述

MainActivity.java

package com.example.userinformation;

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

public class MainActivity extends Activity {
    private EditText nameText, ageText;
    private Button button;
    private Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            String text = "";
            if (msg.what == 1) {
                text = "success";
            } else if (msg.what == 2){
                text = "fail";
            }
            Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        nameText = (EditText) findViewById(R.id.name);
        ageText = (EditText) findViewById(R.id.age);
        button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                final String name = nameText.getText().toString();
                final String age = ageText.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //将EditText中的数据传到服务器
                            boolean result = UserInfoService.save(name, age);
                            if (result == true) {
                                myHandler.sendEmptyMessage(1);
                            } else {
                                myHandler.sendEmptyMessage(2);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }
}

UserInfoService.java

package com.example.userinformation;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class UserInfoService {
    public static boolean save(String name, String age) throws Exception {
        String path = "http://10.107.56.64:8080/ServerGET/ServerGET";
        Map<String, String> params = new HashMap<String, String>();
        params.put("name", name);
        params.put("age", age);
        return sendGETRequest(path, params, "UTF-8");
    }

    private static boolean sendGETRequest(String path,
            Map<String, String> params, String encoding) throws Exception {

        StringBuilder sb = new StringBuilder(path);
        if (params != null && !params.isEmpty()) {
            sb.append("?");
            for (Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey()).append("=");
                sb.append(URLEncoder.encode(entry.getValue(), encoding))
                        .append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        // 上面的sb用来构造url
        HttpURLConnection connection = (HttpURLConnection) new URL(sb.toString())
                .openConnection();
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        if (connection.getResponseCode() == 200) {
            return true;
        }
        return false;
    }
}

测试效果:

这里写图片描述
这里写图片描述
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年04月06日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.web服务端的建立
  • 2.新建servlet
  • 3.编写ServerGET.java
  • 4.测试服务端
  • 5.建立android客户端
相关产品与服务
测试服务
测试服务 WeTest 包括标准兼容测试、专家兼容测试、手游安全测试、远程调试等多款产品,服务于海量腾讯精品游戏,涵盖兼容测试、压力测试、性能测试、安全测试、远程调试等多个方向,立体化安全防护体系,保卫您的信息安全。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档