application/json 與 application/x-www-form-urlencoded的簡單比較

 

在用HttpUrlConnection請求極光推送restful時(http://docs.jiguang.cn/jpush/server/old/rest_api_v2_push/),java

涉及到一個參數序列化問題,對方要求web

HTTP Post 的Content-Type 需採用 application/x-www-form-urlencodedspring

 

而後序列化時用了json(Map.tostring)致使對方的服務器沒有接收到參數,因而改爲 後者,json

代碼參數作了調整segmentfault

 

 

    private static String json2String(JSONObject json) throws UnsupportedEncodingException {
        Iterator<String> sIterator = json.keys();
        String urlpara = "";
        while (sIterator.hasNext()) {
            String key = sIterator.next();
            //根據鍵得到值,值也能夠是JSONObject,JSONArray,使用對應的參數接收便可
            String value = json.getString(key);

            urlpara += key + "=" + URLEncoder.encode(value, "UTF-8") + "&";
        }

        return  urlpara;
    }


doneapi

 

 

(一)緩存

參考:http://blog.csdn.net/mygoon/article/details/48546781bash

 

 

package wzq.j2se;服務器

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

public class HttpURLConnectionPost {

 /**
  * @param args
  * @throws IOException 
  */
 public static void main(String[] args) throws IOException {
  readContentFromPost();
 }
 public static void readContentFromPost() throws IOException {
        // Post請求的url,與get不一樣的是不須要帶參數
        URL postUrl = new URL("http://www.wangzhiqiang87.cn");
        // 打開鏈接
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
      
        // 設置是否向connection輸出,由於這個是post請求,參數要放在
        // http正文內,所以須要設爲true
        connection.setDoOutput(true);
        // Read from the connection. Default is true.
        connection.setDoInput(true);
        // 默認是 GET方式
        connection.setRequestMethod("POST");
       
        // Post 請求不能使用緩存
        connection.setUseCaches(false);
       
        connection.setInstanceFollowRedirects(true);
       
        // 配置本次鏈接的Content-type,配置爲application/x-www-form-urlencoded的
        // 意思是正文是urlencoded編碼過的form參數,下面咱們能夠看到咱們對正文內容使用URLEncoder.encode
        // 進行編碼
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        // 鏈接,從postUrl.openConnection()至此的配置必需要在connect以前完成,
        // 要注意的是connection.getOutputStream會隱含的進行connect。
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection
                .getOutputStream());
        // The URL-encoded contend
        // 正文,正文內容其實跟get的URL中 '? '後的參數字符串一致
        String content = "account=" + URLEncoder.encode("一個大肥人", "UTF-8");
        content +="&pswd="+URLEncoder.encode("兩個個大肥人", "UTF-8");;
        // DataOutputStream.writeBytes將字符串中的16位的unicode字符以8位的字符形式寫到流裏面
        out.writeBytes(content);

        out.flush();
        out.close(); 
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        
        while ((line = reader.readLine()) != null){
            System.out.println(line);
        }
      
        reader.close();
        connection.disconnect();
}

}

在接收端,這樣獲取參數:
String name = request.getParameter("account");
String pswd = request.getParameter("pswd");
 
 System.out.println(new String(name.getBytes("iso-8859-1"),"UTF-8")); 
 System.out.println(new String(pswd.getBytes("iso-8859-1"),"UTF-8"));

 

 

(二)

 

https://segmentfault.com/a/1190000007252829

 

 

application/x-www-form-urlencoded

提交請求示例

curl -X POST 'http://localhost:8080/formPost' -d 'id=1&name=foo&mobile=13612345678'

wireshark抓包結果

 

對應的服務端解析參數源碼

//org.springframework.web.method.annotation.RequestParamMethodArgumentResolver#resolveName
if (arg == null) {
   String[] paramValues = webRequest.getParameterValues(name);
   if (paramValues != null) {
      arg = paramValues.length == 1 ? paramValues[0] : paramValues;
   }
}

application/json

提交請求示例

curl -X POST -H "Content-Type: application/json" 'http://localhost:8080/jsonPost' -d '{"id":2,"name":"foo","mobile":"13656635451"}'

wireshark抓包結果

對應的服務端解析參數源碼

//com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter#readInternal
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();     InputStream in = inputMessage.getBody();
    byte[] buf = new byte[1024]; 
    while(true) {
        int bytes = in.read(buf);         if(bytes == -1) {
            byte[] bytes1 = baos.toByteArray();             return JSON.parseObject(bytes1, 0, bytes1.length, this.charset.newDecoder(), clazz, new Feature[0]);
        }

        if(bytes > 0) {
            baos.write(buf, 0, bytes);         }
    }
}

混用示例

web層代碼

@RequestMapping(value="/mixPost", method=RequestMethod.POST )
    public Result<Void> mixPostTest(@RequestBody @Valid Foo foo, @RequestParam Integer sex)

提交請求

curl -X POST -H "Content-Type: application/json" 'http://localhost:8080/mixPost?sex=1' -d '{"id":2,"name":"foo","mobile":"13656635451"}'

補充--如何定位對應的源碼

找到post請求解析參數源碼

@RequestMapping(value="/formPost", method=RequestMethod.POST )
    public Result<Void> formPostTest(@RequestParam int id, @RequestParam String name, @RequestParam String mobile)

由於id是必填參數 若是請求參數中不含id的話 會報錯 以下所示

org.springframework.web.bind.MissingServletRequestParameterException: Required int parameter 'id' is not present
    at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:255)
    at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:95)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:79)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:157)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:124)

經過此方法能夠快速定位到源碼

找到json請求解析參數的源碼

@RequestMapping(value="/jsonPost", method=RequestMethod.POST )
    public Result<Void> jsonPostTest(@RequestBody @Valid Foo foo)

由於確定要先構造一個空Foo對象 而後才能注入各屬性值 因此在Foo的無參構造函數中加斷點, 能夠定位到json請求解析參數的源碼

相關文章
相關標籤/搜索