# 用Native Java call Rest API 今天的Hackerrank考題真的花太多時間了,來不及寫完,後來用Eclipse重頭思考一次花了一個半小時才寫完, 以後有上機考的題目還是要先用Eclipse親自跑過一次才比較準確。 ```java=\ package practice.java8; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import org.springframework.http.HttpMethod; public class Test { public static void main(String[] args) { getUsernames(10); } public static List<String> getUsernames(int threshold){ List<String> resultList = new ArrayList<>(); String urlStr = "https://jsonmock.hackerrank.com/api/article_users/search?page=2"; try { URL url = new URL(urlStr); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod(HttpMethod.GET.toString()); conn.setRequestProperty("Content-Type", "application/json"); if(conn.getResponseCode() == HttpsURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer response = new StringBuffer(); String inputline = null; while((inputline = in.readLine()) != null) { response.append(inputline); } in.close(); String responseStr = response.toString(); System.out.println("responseStr: "+responseStr); Map resultMap = jsonStringToMap(responseStr); List<Map<Object,Object>> dataList = (List<Map<Object, Object>>) resultMap.get("data"); for(Map<Object,Object> data:dataList) { if((Integer )data.get("submission_count") > threshold) { resultList.add((String) data.get("username")); } } System.out.println(resultList); }else { System.out.println("ERROR: statusCode: "+conn.getResponseCode()); } } catch (Exception e) { System.out.println("ERROR: "+e); } return resultList; } public static Map jsonStringToMap(String jsonStr) throws Exception{ ScriptEngineManager sem = new ScriptEngineManager(); ScriptEngine engine = sem.getEngineByName("javascript"); String script = "Java.asJSONCompatible("+jsonStr+")"; Object result = engine.eval(script); Map content = (Map) result; return content; } } ``` ###### tags: `Java`
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.