Java HttpURLConnection返回JSON

我正在尝试发出一个返回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?

谢谢

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

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

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

使用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实现可用。

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

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

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

你可以试试这个:

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

并且不要忘记将其包装成try-catch

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

 public JSONArray getJSONFromUrl(String endpoint, Map 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> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Map.Entry 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; }