Java HttpURLConnection返回JSON

编程入门 行业动态 更新时间:2024-10-18 01:35:27
本文介绍了Java HttpURLConnection返回JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I'm trying to make a http get request which returns a json response. I need some of the values from the json response to be stored in my session. I have this:

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:

This returns the JSON in a string:

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

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

I need to store StatusCode and CustomerName in the session. How do I deal with returning JSON with java?

谢谢

推荐答案

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

You can use Gson. Here is the code to help you:

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

现在您知道如何从会议中获取并将其放入会议中。 您需要在类路径中包含Gson库。

Now you know how to get from and put those in session. You need to include Gson library in classpath.

更多推荐

Java HttpURLConnection返回JSON

本文发布于:2023-07-14 19:54:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1106671.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Java   HttpURLConnection   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!