curl to java code (HttpURLConnection, URL, JSONparser,JSONObject)

2021. 3. 10. 16:31모바일/Android_Java

curl to java code (HttpURLConnection, URL, JSONparser,JSONObject)

  • 아래와 같은 curl이 있을 때,
curl -H 'Authorization: Basic {인증키}' -XGET 'myurl'

자바코드

        String url = "myurl"
        String authorizationKey = "Basic {인증키}";
        URL urlObject = null;
        HttpURLConnection con = null;
        StringBuffer response = new StringBuffer();

        try {
            urlObject = new URL(url);
            con = (HttpURLConnection) urlObject.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Authorization", authorizationKey);

            int responseCode = con.getResponseCode();
            System.out.println("Response Code : " + responseCode);

            BufferedReader iny = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String output;

            while ((output = iny.readLine()) != null) {
                response.append(output);
            }
            iny.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


        try {
            JSONObject json = new JSONObject(response.toString());
            JSONObject dataJsonObject = json.getJSONObject("data");
            lastPage = Integer.valueOf(dataJsonObject.optString("last_page"));
            JSONArray jsonArray = dataJsonObject.getJSONArray("docs");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                FCStockNewsItem item = new FCStockNewsItem();
                item.sTitle_kor = jsonObject.optString("title", "");
                item.content = jsonObject.optString("content","");
//                item.sProffer = sProffer.trim();
//                item.sNews_Seq = sNews_Seq.trim();
//                item.sDate = sDate.trim();
//                item.sTime = sTime.trim();
//                item.sTitle_eng = sTitle_eng.trim();

//                item.sTrans_yn = sTrans_yn.trim();

                itemList.add(item);
            }
            adapter.notifyDataSetChanged();

        } catch (JSONException e) {
            e.printStackTrace();
        }


//        con.setDoOutput(true);
//        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
//        wr.writeBytes(the data string);
//        wr.flush();
//        wr.close();

        //printing result from response
        //    System.out.println(response.toString());