POS請求API介面樣例

落無痕發表於2019-02-06
package com.api.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Example {
	private static String readAll(Reader rd) throws IOException {
		StringBuilder sb = new StringBuilder();
		int cp;
		while ((cp = rd.read()) != -1) {
		sb.append((char) cp);
		}
		return sb.toString();
		}

		public static JSONObject postRequestFromUrl(String url, String body) throws IOException, JSONException {
		URL realUrl = new URL(url);
		URLConnection conn = realUrl.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		PrintWriter out = new PrintWriter(conn.getOutputStream());
		out.print(body);
		out.flush();

		InputStream instream = conn.getInputStream();
		try {
		 BufferedReader rd = new BufferedReader(new InputStreamReader(instream, Charset.forName("UTF-8")));
		String jsonText = readAll(rd);
		JSONObject json = new JSONObject(jsonText);
		return json;
		} finally {
		instream.close();
		}
		}

		public static JSONObject getRgetRequestFromUrlequestFromUrl(String url) throws IOException, JSONException {
		URL realUrl = new URL(url);
		URLConnection conn = realUrl.openConnection();
		InputStream instream = conn.getInputStream();
		try {
		BufferedReader rd = new BufferedReader(new InputStreamReader(instream, Charset.forName("UTF-8")));
		String jsonText = readAll(rd);
		JSONObject json = new JSONObject(jsonText);
		return json;
		} finally {
		instream.close();
		}
		}
		public static void main(String[] args) throws IOException, JSONException {

		// 請求示例 url 
		String url = "https://www.apiopen.top/journalismApi";
		String body = "";
		JSONObject json = postRequestFromUrl(url,body);
		JSONArray new_json = json.getJSONObject("data").getJSONArray("tech");
		for (int i = 0; i < new_json.length(); i++) {
			JSONObject obj = new_json.getJSONObject(i);
			String title = obj.getString("title");
			String digest = obj.getString("digest");
			System.out.printf("title:%s\rdigest:%s\r",title,digest);
		}
		
		}
}


相關文章