比較 兩種 方式 form 請求 提交 tomcat jetty 接收 參數 區別 post http 調用 欄目 Tomcat 简体版
原文   原文鏈接

[一]瀏覽器form表單提交

表單提交, 適用於瀏覽器提交。像常見的pc端的網銀支付,用戶在商戶商城購買商品,支付時商家系統把交易數據經過form表單提交到三方支付網關,而後用戶在三方網關頁面完成支付。
下面是一個form表單自動提交案例,將這段html輸出到瀏覽器,會自動提交到目標action。html

<form name="payForm" action='http://192.168.40.228:28080/app/userIdentify.do' method='POST' >
    <input type='hidden' name='version' value='B2C1.0'>
    <input type='hidden' name='tranData' value='PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iR0JLIj8+PEIyQ1JlcT48Y2FyZE5vPjE8L2NhcmRObz48Y3VzdG9tZXJOYW1lPkpvaG48L2N1c3RvbWVyTmFtZT48b3JkZXJObz5mZjYxYTk5OC0yN2I0LTQ1YzctOWE0Yi0yYmNlY2ZkNmJmN2E8L29yZGVyTm8+PGNlcnRObz4xMzA0MzQxOTgzMDEwNjc1MTE8L2NlcnRObz48dHJhblR5cGU+MTwvdHJhblR5cGU+PGJhbmtJZD4wPC9iYW5rSWQ+PG1vYmlsZT4xPC9tb2JpbGU+PC9CMkNSZXE+'> 
    <input type='hidden' name='signData' value='c3c50a27dac38c123c4be418b2273049'> 
    <input type='hidden' name='merchantId' value='M100001564'>
    <input type='submit' value='提交' />
    <script>document.forms['payForm'].submit();</script>
</form>

 

[二]服務端httppost

另外一種是服務端點對點的http協議的post請求,此方式適用於api接口調用。將請求數據以querystring的格式(a=val1&b=val2&c=val3&...)做爲參數傳(提)輸(交)給服務端。此時注意要把Request的Content-Type設置爲application/x-www-form-urlencoded。以下是一個工具方法:java

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *
 * HTTP協議POST請求方法
 */
public static String httpMethodPost(String url, String params, String gb) {
    if (null == gb || "".equals(gb)) {
        gb = "UTF-8";
    }
    StringBuffer sb = new StringBuffer();
    URL urls;
    HttpURLConnection uc = null;
    BufferedReader in = null;
    try {
        urls = new URL(url);
        uc = (HttpURLConnection) urls.openConnection();
        uc.setRequestMethod("POST");
        uc.setDoOutput(true);
        uc.setDoInput(true);
        uc.setUseCaches(false);
        uc.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        uc.connect();
        if(!StringUtils.isBlank(params)){
            DataOutputStream out = new DataOutputStream(uc.getOutputStream());
            out.write(params.getBytes(gb));
            out.flush();
            out.close();
        }
        in = new BufferedReader(new InputStreamReader(uc.getInputStream(),
                gb));
        String readLine = "";
        while ((readLine = in.readLine()) != null) {
            sb.append(readLine);
        }
        if (in != null) {
            in.close();
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
    return sb.toString();
}


調用方式:apache

String url = "http://192.168.40.228:28080/app/userIdentify.do";
String param = String.format("version=%s&tranData=%s&signData=%s&merchantId=%s", version, URLEncoder.encode(tranDataBase64, "GBK"), signData, merchantId);
String responseStr = HttpUtil.httpMethodPost(url, param, "GBK");

 

[三]服務端httppost的另外一種實現

另外一種是針對於util方法暴露的參數是Map的場景:api

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public final class HttpUtil {

    public static String httpMethodPost(String url, Map<String, String> paramMap) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        boolean var3 = true;

        byte result;
        try {
            HttpPost post = new HttpPost(url);
            UrlEncodedFormEntity uefEntity = null;
            List<NameValuePair> list = new ArrayList();
            if (null != paramMap) {
                Iterator var7 = paramMap.entrySet().iterator();

                while (var7.hasNext()) {
                    Map.Entry<String, String> entity = (Map.Entry) var7.next();
                    list.add(new BasicNameValuePair((String) entity.getKey(), (String) entity.getValue()));
                }

                uefEntity = new UrlEncodedFormEntity(list, "UTF-8");
                post.setEntity(uefEntity);
            }

            System.out.println("POST 請求...." + post.getURI());
            CloseableHttpResponse httpResponse = httpClient.execute(post);
            StatusLine statusLine = httpResponse.getStatusLine();
            System.out.println(statusLine);

            try {
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity, "UTF-8");
                }
            } finally {
                httpResponse.close();
            }

        } catch (Exception var25) {
            var25.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception var23) {
                var23.printStackTrace();
            }
        }

        return null;
    }
}

 

[三]服務端參數獲取方式

ServletRequest對象的以下方法:
    ServletInputStream getInputStream() throws IOException;

    String getParameter(String var1);

    Enumeration getParameterNames();

    String[] getParameterValues(String var1);

    Map getParameterMap();

 

結束

 

 

▄︻┻┳═一tomcat與jetty接收請求參數的區別瀏覽器

▄︻┻┳═一比較兩種方式的form請求提交tomcat

▄︻┻┳═一Post方式的Http流請求調用app

相關文章
相關標籤/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。
本站公眾號
   歡迎關注本站公眾號,獲取更多信息