org.json - HTTP

HTTP 类提供静态方法将 Web 浏览器的标头文本转换为 JSONObject,反之亦然。

示例中涵盖了以下方法。

  • toJSONObject(String) − 将标头文本转换为 JSONObject 对象。

  • toString(JSONObject) − 将 JSONObject 转换为标头文本。

示例

import org.json.HTTP;
import org.json.JSONObject;

public class JSONDemo {
   public static void main(String[] args) { 
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("Method", "POST");
      jsonObject.put("Request-URI", "http://www.tutorialspoint.com/");
      jsonObject.put("HTTP-Version", "HTTP/1.1");
        
      //案例 1:将标头的 JSONObject 转换为字符串
      String headerText = HTTP.toString(jsonObject);
      System.out.println(headerText); 
        
      headerText = "POST \"http://www.tutorialspoint.com/\" HTTP/1.1";
      //案例 2:将标头字符串转换为 JSONObject
      System.out.println(HTTP.toJSONObject(headerText));
   }
}

输出

POST "http://www.tutorialspoint.com/" HTTP/1.1

{"Request-URI":"http://www.tutorialspoint.com/","Method":"POST","HTTP-Version":"HTTP/1.1"}