- package sn.len.getandpostreq;
- import java.util.HashMap;
- import java.util.Map;
- import sn.len.request.RequestService;
- import Android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.EditText;
- import android.widget.Toast;
- public class GetAndPostRequestActivity extends Activity implements OnClickListener
- {
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- View get_button=findViewById(R.id.get_reqeust);
- View post_button=findViewById(R.id.post_reqeust);
- get_button.setOnClickListener(this);
- post_button.setOnClickListener(this);
- }
- @Override
- public void onClick(View v)
- {
- EditText book_name=(EditText)findViewById(R.id.book_name);
- EditText book_price=(EditText)findViewById(R.id.book_price);
- String bookname=book_name.getText().toString();
- String bookprice=book_price.getText().toString();
- switch(v.getId())
- {
- case R.id.get_reqeust: //Get请求
- {
- //第一种可以用字符串拼接
- String urlPath="http://192.168.0.133/web/index.jsp"+"?type=save&book_name="+bookname+"&book_price="+bookprice+"";
- String realPath=urlPath.replaceAll(" ", "");//把多余的空格替换掉
- try
- {
- if(RequestService.getRequest(realPath))
- {
- Toast.makeText(this, R.string.success, Toast.LENGTH_LONG).show();
- }
- }
- catch (Exception e)
- {
- Toast.makeText(this, R.string.error, Toast.LENGTH_LONG).show();
- e.printStackTrace();
- }
- }break;
- case R.id.post_reqeust: //Post请求
- {
- String urlPath="http://192.168.0.133/web/index.jsp";
- Map<String,String> map=new HashMap<String,String>();//用集合来做,比字符串拼接来得直观
- map.put("type", "save");
- map.put("book_name",bookname);
- map.put("book_price",bookprice);
- try
- {
- if(RequestService.postRequest(urlPath, map))
- {
- Toast.makeText(this, R.string.success, Toast.LENGTH_LONG).show();
- }
- }
- catch (Exception e)
- {
- Toast.makeText(this, R.string.error, Toast.LENGTH_LONG).show();
- Log.e("ERRORS", e.toString());
- e.printStackTrace();
- }
- }break;
- default:break;
- }
- }
- }
- <%@page contentType="text/html" pageEncoding="GBK" language="java"%>
- <%
- String type=request.getParameter("type");
- if(type!=null && !"".equals(type))
- {
- if(type.equals("save"))
- {
- String book_name=request.getParameter("book_name");
- String book_price=request.getParameter("book_price");
- if((book_name!=null && !"".equals(book_name)) && (book_price!=null && !"".equals(book_price)))
- {
- System.out.println("书名"+book_name);
- System.out.println("价格"+book_price);
- }
- }
- }
- %>

//Tomcat服务端响应效果,书名和价格都已经打出来了。

