buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

比较两种方式的form请求提交

[一]浏览器form表单提交

表单提交, 适用于浏览器提交。像常见的pc端的网银支付,用户在商户商城购买商品,支付时商家系统把交易数据通过form表单提交到三方支付网关,然后用户在三方网关页面完成支付。
下面是一个form表单自动提交案例,将这段html输出到浏览器,会自动提交到目标action。

<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.net.URL实现的工具方法:

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 charset) {
    if (null == charset || "".equals(charset)) {
        charset = "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(charset));
            out.flush();
            out.close();
        }
        in = new BufferedReader(new InputStreamReader(uc.getInputStream(), charset));
        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();
}


调用方式:

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的场景,这时我们借助org.apache.httpcomponents:httpclient里的org.apache.http.client.methods.HttpPost来实现。

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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 static String httpMethodPost(String url, Map<String, String> paramMap) {
    try {
        HttpPost post = new HttpPost(url);
        List<NameValuePair> list = new ArrayList<>();
        if (null != paramMap) {
            for (Map.Entry<String, String> entity : paramMap.entrySet()) {
                list.add(new BasicNameValuePair(entity.getKey(), entity.getValue()));
            }

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

        System.out.println("POST 请求...." + post.getURI());
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse httpResponse = httpClient.execute(post)
        ) {
            System.out.println("statusLine=" + httpResponse.getStatusLine());//正常情况StatusLine是:HTTP/1.1 200 OK

            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity, "UTF-8");
            }
        };
        
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

 

 

[四]服务端参数获取方式

ServletRequest对象有如下方法可供我们使用:
    ServletInputStream getInputStream() throws IOException;

    String getParameter(String var1);

    Enumeration getParameterNames();

    String[] getParameterValues(String var1);

    Map getParameterMap();

 

EOF

 

 

▄︻┻┳═一tomcat与jetty接收请求参数的区别

▄︻┻┳═一比较两种方式的form请求提交

▄︻┻┳═一Post方式的Http流请求调用

posted on 2018-06-19 15:37  buguge  阅读(879)  评论(0编辑  收藏  举报