【问题标题】:How to pass a JSON Object in HTTPURLConnection如何在 HTTPURLConnection 中传递 JSON 对象
【发布时间】:2012-01-10 12:06:59
【问题描述】:

我正在使用 org.json.simple.JSONObject。我想使用 HTTPURLConnection 传递一个 JSONObject。我该怎么做?

【问题讨论】:

    标签: json playframework


    【解决方案1】:

    这个答案可能已经晚了,但为了以防万一,我将粘贴在我用于该目标的代码下方:

    URL url;
    HttpURLConnection urlConnection = null;
     try {
      url = new URL(SOME URL...);
      JSONObject reqJson = THE JSON OBJECT TO BE PASSED...;
      urlConnection = (HttpURLConnection) url.openConnection();
      urlConnection.setDoOutput(true);
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
      bw.write(reqJson.toString());
      bw.flush();
      bw.close();
    
      //Now handle response
      BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
       ...
       ...
    
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
        urlConnection.disconnect();
    }
    

    【讨论】:

      【解决方案2】:

      为什么不使用play.libs.WS类,并将这个JSON对象作为字符串设置为指定的参数名称。

      【讨论】:

      • 由于某些限制,我无法使用 WS
      【解决方案3】:

      我将 JSONObject 转换为字符串,并将字符串转换为目标中的 JSONObject。至少现在。

      【讨论】:

      猜你喜欢
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 2019-11-15
      • 2013-01-21
      • 2015-04-05
      相关资源
      最近更新 更多