GET和POST方式提交參數給web應用

服務器端:html

新建一個名爲ManagerServlet的Servlet:java

package cn.leigo.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ManagerServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String title = request.getParameter("title");
		String timelength = request.getParameter("timelength");
		System.out.println("標題:" + title);
		System.out.println("時長:" + timelength + "分鐘");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

}

  

運行後控制檯打印:android

Android客戶端:web

LinearLayout 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:background="@android:color/background_dark"  
    android:orientation="vertical"  
    tools:context=".MainActivity" >  
  
    <TextView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="@string/title"  
        android:textColor="@android:color/white"  
        android:textSize="20sp" />  
  
    <EditText  
        android:id="@+id/et_title"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:inputType="text" />  
  
    <TextView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="@string/timelength"  
        android:textColor="@android:color/white"  
        android:textSize="20sp" />  
  
    <EditText  
        android:id="@+id/et_timelength"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:inputType="number" />  
  
    <Button  
        android:id="@+id/btn_save"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="@string/save" />  
  
</LinearLayout>  

  strings.xml:服務器

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
  
    <string name="app_name">資訊管理</string>  
    <string name="action_settings">Settings</string>  
    <string name="hello_world">Hello world!</string>  
    <string name="title">資訊標題</string>  
    <string name="timelength">資訊時長</string>  
    <string name="save">保存</string>  
    <string name="success">保存成功!</string>  
    <string name="fail">保存失敗!</string>  
    <string name="error">資訊標題和資訊時長不能爲空!</string>  
  
</resources>  

  MainActivity.java:app

package cn.leigo.newsmanager;  
  
import cn.leigo.service.NewsService;  
import android.app.Activity;  
import android.os.Bundle;  
import android.text.TextUtils;  
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 implements OnClickListener {  
    private EditText mTitleEditText;  
    private EditText mTimelengthEditText;  
    private Button mSaveButton;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        mTitleEditText = (EditText) findViewById(R.id.et_title);  
        mTimelengthEditText = (EditText) findViewById(R.id.et_timelength);  
        mSaveButton = (Button) findViewById(R.id.btn_save);  
        mSaveButton.setOnClickListener(this);  
    }  
  
    @Override  
    public void onClick(View v) {  
        String title = mTitleEditText.getText().toString();  
        String timelength = mTimelengthEditText.getText().toString();  
        if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(timelength)) {  
            boolean isSuccess = NewsService.save(title, timelength);  
            if (!isSuccess) {  
                Toast.makeText(this, R.string.fail, Toast.LENGTH_SHORT).show();  
            } else {  
                Toast.makeText(this, R.string.success, Toast.LENGTH_SHORT)  
                        .show();  
            }  
        } else {  
            Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();  
        }  
    }  
  
}  

  NewsService.java:jsp

package cn.leigo.service;  
  
import java.io.IOException;  
import java.net.HttpURLConnection;  
import java.net.URL;  
import java.util.HashMap;  
import java.util.Map;  
  
public class NewsService {  
  
    /** 
     * 保存數據 
     *  
     * @param title 
     *            標題 
     * @param timelength 
     *            時長 
     * @return 請求是否成功 
     */  
    public static boolean save(String title, String timelength) {  
        String path = "http://192.168.1.100:8080/videonews/ManagerServlet";  
        Map<String, String> params = new HashMap<String, String>();  
        params.put("title", title);  
        params.put("timelength", timelength);  
        try {  
            return sendGETRequest(path, params);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return false;  
    }  
  
    /** 
     * 發送GET請求 
     *  
     * @param path 
     *            請求路徑 
     * @param params 
     *            請求參數 
     * @return 
     * @throws IOException 
     */  
    private static boolean sendGETRequest(String path,  
            Map<String, String> params) throws IOException {  
        // http://192.168.1.100:8080/videonews/ManagerServlet?title=abc&timelength=30  
        StringBuilder url = new StringBuilder(path);  
        url.append("?");  
        for (Map.Entry<String, String> entry : params.entrySet()) {  
            url.append(entry.getKey());  
            url.append("=");  
            url.append(entry.getValue());  
            url.append("&");  
        }  
        url.deleteCharAt(url.length() - 1);  
        HttpURLConnection conn = (HttpURLConnection) new URL(url.toString())  
                .openConnection();  
        conn.setConnectTimeout(5000);  
        conn.setRequestMethod("GET");  
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {  
            return true;  
        }  
        return false;  
    }  
}  

  運行:ide

產生亂碼緣由:post

1)在提交參數時,沒有對中文參數進行URL編碼測試

url.append(URLEncoder.encode(entry.getValue(), encoding));  

  修改後繼續測試,運行

2)Tomcat服務器默認採用的是ISO8859-1編碼獲得參數值

String title = request.getParameter("title");  
title = new String(title.getBytes("ISO8859-1"), "UTF-8");  

通過這兩步處理後,中文亂碼問題獲得瞭解決,可是出現一個問題,在第二步中,若是字符串有不少,每次都用

new String(title.getBytes("ISO8859-1"), "UTF-8");  

這中方式解決很麻煩,我們能夠定義一個過濾器對每次穿過來的參數進行編碼

 

EncodingFilter.java:

package cn.leigo.filter;  
  
import java.io.IOException;  
  
import javax.servlet.Filter;  
import javax.servlet.FilterChain;  
import javax.servlet.FilterConfig;  
import javax.servlet.ServletException;  
import javax.servlet.ServletRequest;  
import javax.servlet.ServletResponse;  
import javax.servlet.http.HttpServletRequest;  
  
import cn.leigo.servlet.EncodingHttpServletRequest;  
  
public class EncodingFilter implements Filter {  
  
    public void destroy() {  
  
    }  
  
    public void doFilter(ServletRequest request, ServletResponse response,  
            FilterChain chain) throws IOException, ServletException {  
        HttpServletRequest req = (HttpServletRequest) request;  
        if ("GET".equals(req.getMethod())) {  
            EncodingHttpServletRequest wrapper = new EncodingHttpServletRequest(  
                    req);  
            chain.doFilter(wrapper, response);  
        } else {  
            chain.doFilter(request, response);  
        }  
    }  
  
    public void init(FilterConfig filterConfig) throws ServletException {  
  
    }  
  
}  
EncodingHttpServletRequest.java:
package cn.leigo.servlet;  
  
import java.io.UnsupportedEncodingException;  
  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletRequestWrapper;  
  
public class EncodingHttpServletRequest extends HttpServletRequestWrapper {  
  
    private HttpServletRequest request;  
  
    public EncodingHttpServletRequest(HttpServletRequest request) {  
        super(request);  
        this.request = request;  
    }  
  
    @Override  
    public String getParameter(String name) {  
        String value = request.getParameter(name);  
        if (value != null) {  
            try {  
                value = new String(value.getBytes("ISO8859-1"), "UTF-8");  
            } catch (UnsupportedEncodingException e) {  
            }  
        }  
  
        return value;  
    }  
  
}  

下面咱們來看看使用POST方式提交數據

 

在WEB-INF下修改index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>Insert title here</title>  
</head>  
<body>  
    <form action="/web/ManageServlet" method="post">  
        視頻標題:<input name="title" type="text"><br/>  
        視頻時長:<input name="timelength" type="text"><br/>  
        <input type="submit" value=" 提 交 "/>  
    </form>  
</body>  
</html>  

修改ManagerSevlet.java:

public void doPost(HttpServletRequest request, HttpServletResponse response)  
        throws ServletException, IOException {  
    doGet(request, response);  
}  

點擊提交

 

在firebug中查看信息

 

/** 
     * 發送POST請求 
     *  
     * @param path 
     *            請求路徑 
     * @param params 
     *            請求參數 
     * @param encoding 
     *            編碼 
     * @return 請求是否成功 
     * @throws IOException 
     */  
    private static boolean sendPOSTRequest(String path,  
            Map<String, String> params, String encoding) throws IOException {  
        // title=leigo&timelength=45 Content-Length 25 Content-Type  
        // application/x-www-form-urlencoded  
        StringBuilder data = new StringBuilder();  
        if (params != null && !params.isEmpty()) {  
            for (Map.Entry<String, String> entry : params.entrySet()) {  
                data.append(entry.getKey());  
                data.append("=");  
                data.append(URLEncoder.encode(entry.getValue(), encoding));  
                data.append("&");  
            }  
            data.deleteCharAt(data.length() - 1);  
        }  
        byte[] entity = data.toString().getBytes(); // 生成實體數據  
        HttpURLConnection conn = (HttpURLConnection) new URL(path)  
                .openConnection();  
        conn.setConnectTimeout(5000);  
        conn.setRequestMethod("POST");  
        conn.setDoOutput(true); // 容許對外輸出數據  
        conn.setRequestProperty("Content-Type",  
                "application/x-www-form-urlencoded");  
        conn.setRequestProperty("Content-Length", String.valueOf(entity.length));  
        OutputStream outputStream = conn.getOutputStream();  
        outputStream.write(entity);  
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {  
            return true;  
        }  
        return false;  
    }  

防亂碼:

if ("GET".equals(req.getMethod())) {  
            EncodingHttpServletRequest wrapper = new EncodingHttpServletRequest(  
                    req);  
            chain.doFilter(wrapper, response);  
        } else {  
            req.setCharacterEncoding("UTF-8");  
            chain.doFilter(request, response);  
        }  

/** 
     * 經過HttpClient發送請求 
     *  
     * @param path 
     *            請求路徑 
     * @param params 
     *            請求參數 
     * @param encoding 
     *            編碼 
     * @return 請求是否成功 
     * @throws IOException 
     */  
    private static boolean sendHttpClientPOSTRequest(String path,  
            Map<String, String> params, String encoding) throws IOException {  
        List<NameValuePair> pairs = new ArrayList<NameValuePair>(); // 存放請求參數  
        for (Map.Entry<String, String> entry : params.entrySet()) {  
            BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(),  
                    entry.getValue());  
            pairs.add(pair);  
        }  
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encoding);  
        HttpPost httpPost = new HttpPost(path);  
        httpPost.setEntity(entity);  
        DefaultHttpClient client = new DefaultHttpClient();  
        HttpResponse response = client.execute(httpPost);  
        if (response.getStatusLine().getStatusCode() == 200) {  
            return true;  
        }  
        return false;  
    }  

煮酒聲明: 文章轉自:http://blog.csdn.net/le_go/article/details/9295327

相關文章
相關標籤/搜索