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

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;
    }
}

测试效果:
这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值