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());
'모바일 > Android_Java' 카테고리의 다른 글
[Android] ViewPager 화면에 보일 때 호출 (setUserVisibleHint함수, mIsVisibleToUser변수) (0) | 2021.04.01 |
---|---|
[java] sns 형태 시간 (몇분전)으로 변경하기 (0) | 2021.03.26 |
[Android] onNewIntent, onSaveInstanceState (0) | 2021.03.10 |
[android] theme, attr, style, color ,values 정리 (0) | 2021.02.26 |
TabLayout Custom View View 안에있는 TextView Selected 안될때 해결법! (0) | 2021.02.25 |