/** * 内部通信请求 * * @param url 远程请求的URL * @param param 远程请求参数 * @return 远程请求返回的JSON */ public static JSONArray sendPostUrl(String url, String param) { PrintWriter out = null; BufferedReader in = null; JSONArray jsonObject = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流(设置请求编码为UTF-8) out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 获取请求返回数据(设置返回数据编码为UTF-8) in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; while ((line = in.readLine()) != null) { result += line; } jsonObject = JSONArray.fromObject(result); } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return jsonObject; }
/**
*调用方法返回JSONArray 数据
*/
JSONArray jsonArray = sendPostUrl(requestURL, null);
/**
*JSONArray 数据解析
*/
if (jsonArray.size() > 0) { for (int i = 0; i < jsonArray.size(); i++) { // 遍历 jsonarray 数组,把每一个对象转成 JSONObject 对象 JSONObject job = jsonArray.getJSONObject(i); // 得到 每个对象中的属性值 string result = job.get("result "); } }