Java HttpURLConnection返回JSON

5

我正在尝试进行HTTP GET请求,该请求返回JSON响应。 我需要将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?

谢谢

6个回答

7
使用JSON库。这是使用Jackson的示例:
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 Schema。有Java实现可用。

完全不同的问题,但是从一个JSP页面发出请求并获取响应是否可能? - user1375026
当然。选择技术取决于您。 - fge
从未听说过ObjectMapper。它是什么? - IgorGanapolsky
@IgorGanapolsky 在 Jackson 中,这是一个方便的入口点,用于 JSON 解析(到 JsonNode 或 POJO)和许多其他事情。真的没有明确定义的角色 :) - fge

3

对于会话存储,您可以使用应用程序上下文类: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;
}

1
不应该将 httpURLConnection.disconnect(); 放在 finally 块中,这会显示“httpURLConnection 可能未初始化”错误,请将其放在 try 块中。顺便说一句,回答很好。 - Apurva
1
在 finally 块中,只需关闭流而不是连接。正如 Zorn 先生所说,可以查看 GSON 库以进行 Json<->Object 转换。 - Solostaran14

1
你可以尝试这个:

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

而且不要忘记将它包装在try-catch中


1
你可以使用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库。

1

0

我的方法使用调用服务或异步任务中的参数

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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接