【问题标题】:Java HttpURLConnection Returns JSONJava HttpURLConnection 返回 JSON
【发布时间】:2013-01-06 18:30:05
【问题描述】:

我正在尝试发出一个返回 json 响应的 http get 请求。我需要将 json 响应中的一些值存储在我的会话中。我有这个:

public String getSessionKey(){
    BufferedReader rd  = null;
    StringBuilder sb = null;
    String line = null;
    try {
         URL url = new URL(//url here);
         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
         connection.setRequestMethod("GET");
         connection.connect();
         rd  = new BufferedReader(new InputStreamReader(connection.getInputStream()));
          sb = new StringBuilder();

          while ((line = rd.readLine()) != null)
          {
              sb.append(line + '\n');
          }
          return sb.toString();

     } catch (MalformedURLException e) {
         e.printStackTrace();
     } catch (ProtocolException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     }

    return "";
}

这会以字符串形式返回 JSON:

{ "StatusCode": 0, "StatusInfo": "Processed and Logged OK", "CustomerName": "Mr API"}

我需要在会话中存储 StatusCode 和 CustomerName。如何处理用 java 返回的 JSON?

谢谢

【问题讨论】:

    标签: java json http request


    【解决方案1】:

    使用 JSON 库。这是杰克逊的一个例子:

    ObjectMapper mapper = new ObjectMapper();
    
    JsonNode node = mapper.readTree(connection.getInputStream());
    
    // Grab statusCode with node.get("StatusCode").intValue()
    // Grab CustomerName with node.get("CustomerName").textValue()
    

    请注意,这不会检查返回的 JSON 的有效性。为此,您可以使用 JSON 模式。有可用的 Java 实现。

    【讨论】:

    • 完全不同的问题,但是否可以发出请求并从 jsp 页面获取响应?
    • 当然是。技术的选择取决于您,真的。
    • 从未听说过 ObjectMapper。这是什么?
    • @IgorGanapolsky in Jackson,这是 JSON 解析(到 JsonNodes 或 POJO)和许多其他东西的便捷入口点。没有明确定义的角色,真的:)
    【解决方案2】:

    对于会话存储,您可以使用应用程序上下文类:Application,或使用静态全局变量。

    要从 HttpURLConnection 解析 JSON,您可以使用如下方法:

    public JSONArray getJSONFromUrl(String url) {
        JSONArray jsonArray = null;
    
        try {
            URL u = new URL(url);
            httpURLConnection = (HttpURLConnection) u.openConnection();
            httpURLConnection.setRequestMethod("GET");
            bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            stringBuilder = new StringBuilder();
    
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line + '\n');
            }
            jsonString = stringBuilder.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpURLConnection.disconnect();
        }
    
        try {
            jsonArray = new JSONArray(jsonString);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
        return jsonArray;
    }
    

    【讨论】:

    • 你不应该把httpURLConnection.disconnect();放在finally块里,它会告诉你httpURLConnection可能没有被初始化错误,把它放在try块里。顺便说一句,很好的答案。
    • 在 finally 块中,只关闭流而不是连接。正如 Zorn 先生所说,请查看 GSON 库以进行 Json对象转换。
    【解决方案3】:

    您可以使用 Gson。以下是可以帮助您的代码:

    Map<String, Object> jsonMap;  
    Gson gson = new Gson();  
    Type outputType = new TypeToken<Map<String, Object>>(){}.getType();  
    jsonMap = gson.fromJson("here your string", outputType);
    

    现在您知道如何从会话中获取它们并将它们置于会话中。 您需要在类路径中包含 Gson 库

    【讨论】:

      【解决方案4】:

      查看 GSON 库以将 json 转换为对象,反之亦然。

      http://code.google.com/p/google-gson/

      【讨论】:

        【解决方案5】:

        你可以试试这个:

        JSONObject json = new JSONObject(new JSONTokener(sb.toString()));
        json.getInt("StatusCode");
        json.getString("CustomerName");
        

        别忘了把它包装到 try-catch 中

        【讨论】:

          【解决方案6】:

          我的方法用参数在调用中使用Service或AsyncTask

          public JSONArray getJSONFromUrl(String endpoint, Map<String, String> params)
                  throws IOException
          {
              JSONArray jsonArray = null;
              String jsonString = null;
              HttpURLConnection conn = null;
              String line;
          
              URL url;
              try
              {
                  url = new URL(endpoint);
              }
              catch (MalformedURLException e)
              {
                  throw new IllegalArgumentException("invalid url: " + endpoint);
              }
          
              StringBuilder bodyBuilder = new StringBuilder();
              Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
              // constructs the POST body using the parameters
              while (iterator.hasNext())
              {
                  Map.Entry<String, String> param = iterator.next();
                  bodyBuilder.append(param.getKey()).append('=')
                          .append(param.getValue());
                  if (iterator.hasNext()) {
                      bodyBuilder.append('&');
                  }
              }
          
              String body = bodyBuilder.toString();
              byte[] bytes = body.getBytes();
              try {
          
                  conn = (HttpURLConnection) url.openConnection();
                  conn.setDoOutput(true);
                  conn.setUseCaches(false);
                  conn.setFixedLengthStreamingMode(bytes.length);
                  conn.setRequestMethod("POST");
                  conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
                  // post the request
                  OutputStream out = conn.getOutputStream();
                  out.write(bytes);
                  out.close();
                  // handle the response
                  int status = conn.getResponseCode();
          
                  if (status != 200) {
                      throw new IOException("Post failed with error code " + status);
                  }
          
                  BufferedReader  bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                  StringBuilder stringBuilder = new StringBuilder();
          
          
                  while ((line = bufferedReader.readLine()) != null)
                  {
                      stringBuilder.append(line + '\n');
                  }
          
                  jsonString = stringBuilder.toString();
              } catch (MalformedURLException e) {
                  e.printStackTrace();
              } catch (ProtocolException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              } finally {
                  conn.disconnect();
              }
          
              try {
                  jsonArray = new JSONArray(jsonString);
              } catch (JSONException e) {
                  e.printStackTrace();
              }
          
              return jsonArray;
          }
          

          【讨论】:

            猜你喜欢
            • 2018-06-30
            • 1970-01-01
            • 2012-07-17
            • 2015-03-19
            • 2016-07-24
            • 1970-01-01
            • 2023-04-07
            • 2016-04-04
            • 2022-01-11
            相关资源
            最近更新 更多