Google 에서 다운로드 Talend API Tester -> 포스트맨 대신 사용
가상의 json 파일 :
https://jsonplaceholder.typicode.com/
https://github.com/google/gson
implementation 'com.google.code.gson:gson:2.9.0'
코드 추가
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
MainActivity.java
package com.example.myhttpconnection;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.example.myhttpconnection.models.Person;
import com.example.myhttpconnection.models.User;
import com.example.myhttpconnection.models.response.ResTodo;
import com.example.myhttpconnection.service.UserService;
import com.example.myhttpconnection.utils.HttpClient;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private static String TAG = "TAG";
ArrayList<Person> personArrayList;
ArrayList<ResTodo> todos;
TextView textView;
HttpClient httpClient;
User user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UserService userService = new UserService();
user = userService.read("10");
}
private void requestTodos() {
new Thread(() -> {
try {
todos = httpClient.todos("/todos");
Log.d(TAG, "todos : " + todos.toString());
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
private void savePost() {
new Thread(() -> {
try {
httpClient.posts("/posts");
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
/**
* JSON Object
* JSON Array
*/
private void testCodeForJson() {
// 1. 하나의 jsonObject 만들기
// 2. JSON Array 만들기
// JSON Object 형태로 만들어 주는 녀석
// { key : value }
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
try {
jsonObject.put("이름", "홍길동");
jsonObject.put("나이", 30);
jsonObject.put("직업", "개발자");
jsonObject.put("취미", "게임");
jsonObject.put("결혼여부", false);
jsonArray.put(jsonObject);
jsonArray.put(jsonObject);
jsonArray.put(jsonObject);
// Log.d(TAG, jsonArray.toString());
// 사용해 보기
// 1. JSON OBJECT 파싱 하기
// Log.d(TAG, jsonObject.toString());
// Person person = new Gson().fromJson(jsonObject.toString(), Person.class);
// Log.d(TAG, person.get이름());
// Log.d(TAG, person.get나이() + "");
// 2. JSON Array 파싱 하기 !
// Person[] people = new Gson().fromJson(jsonArray.toString(), Person[].class);
// Log.d(TAG, Arrays.toString(people));
// 3. ArrayList 로 파싱하는 방법
Type listType = new TypeToken<ArrayList<Person>>(){}.getType();
personArrayList = new Gson().fromJson(jsonArray.toString(), listType);
Log.d(TAG, personArrayList.get(0).toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* 자바, 안드로이에서 통신프로토을을 활용해서
* 서버측에 데이터를 요청해서 응답 (HTTP)
*/
private void httpConnectionTestCode() {
// 익명클래스로 쓰래드 만들기
new Thread(new Runnable() {
@Override
public void run() {
// 1. 준비물 URL 객체 필요
String baseUrl = "https://jsonplaceholder.typicode.com/";
String endPoint = "todos/1";
try {
// Http Request Message 생성 (시작줄 + http header)
URL url = new URL(baseUrl + endPoint);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); // GET, POST, PUT, DELETE
// 결과값 받기
// 1. 응답 코드 받기
// 상태코드 1xx(진행중), 2xx(성공), 3xx(리다렉트), 4xx(실패: 잘못된요청), 500(연산오류)
// GET 성공 ---> 200 호출
// POST 성공 ---> 201 호출
Log.d("TAG", "상태코드 받아 보기 " + conn.getResponseCode());
// 응답 바디 데이터 받아 보기
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream())
);
// Dto
ResTodo todo = new Gson().fromJson(reader, ResTodo.class);
Log.d(TAG, todo.toString()); // -> 주소값 :: --> 오버라이드 처리
Log.d(TAG, todo.getTitle());
Log.d(TAG, todo.getBody());
// String line = null;
// StringBuffer sb = new StringBuffer();
// while ( (line = reader.readLine()) != null ) {
// sb.append(line +"\n");
// }
// Log.d(TAG, sb.toString());
// String responseResult = sb.toString();
// String key = responseResult.substring(3, 10);
// String value = responseResult.substring(11, 14);
// Log.d(TAG, "key : " + key);
// Log.d(TAG, "value : " + value);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
SubActivity.java
package com.example.myhttpconnection;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.myhttpconnection.service.TodoService;
public class SubActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
TodoService todoService = new TodoService();
//Todo todo = todoService.read();
// 화면 만드는 부분 집중
}
}
models.pac>
request.pac>
ReqPost.java
package com.example.myhttpconnection.models.request;
public class ReqPost {
private String title;
private String body;
private int userId;
public ReqPost(String title, String body, int userId) {
this.title = title;
this.body = body;
this.userId = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
models.pac>
response.pac>
r-1. ResPost.java
r-2. ResTodo.java
r-1.
package com.example.myhttpconnection.models.response;
public class ResPost {
private int id;
private String title;
private String body;
private int userId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@Override
public String toString() {
return "ResPost{" +
"id=" + id +
", title='" + title + '\'' +
", body='" + body + '\'' +
", userId=" + userId +
'}';
}
}
r-2.
package com.example.myhttpconnection.models.response;
public class ResTodo {
private int userId;
private int id;
private String title;
private String body;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
@Override
public String toString() {
return "ResTodo{" +
"userId=" + userId +
", id=" + id +
", title='" + title + '\'' +
", body='" + body + '\'' +
'}';
}
}
models.pac>
m-1. Person.java
m-2. User.java
m-1.
package com.example.myhttpconnection.models;
public class Person {
String 이름;
int 나이;
String 직업;
String 취미;
Boolean 결혼여부;
public String get이름() {
return 이름;
}
public void set이름(String 이름) {
this.이름 = 이름;
}
public int get나이() {
return 나이;
}
public void set나이(int 나이) {
this.나이 = 나이;
}
public String get직업() {
return 직업;
}
public void set직업(String 직업) {
this.직업 = 직업;
}
public String get취미() {
return 취미;
}
public void set취미(String 취미) {
this.취미 = 취미;
}
public Boolean get결혼여부() {
return 결혼여부;
}
public void set결혼여부(Boolean 결혼여부) {
this.결혼여부 = 결혼여부;
}
@Override
public String toString() {
return "Person{" +
"이름='" + 이름 + '\'' +
", 나이=" + 나이 +
", 직업='" + 직업 + '\'' +
", 취미='" + 취미 + '\'' +
", 결혼여부=" + 결혼여부 +
'}';
}
}
m-2.
package com.example.myhttpconnection.models;
public class User {
private int id;
private String name;
private String username;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", username='" + username + '\'' +
", email='" + email + '\'' +
'}';
}
}
repository.pac>
re-1. TodoRepository.interface
re-2. UserRepository.interface
re-1.
package com.example.myhttpconnection.repository;
public interface TodoRepository {
void create();
void read();
void update();
void delete();
}
re-2.
package com.example.myhttpconnection.repository;
import com.example.myhttpconnection.models.User;
public interface UserRepository {
// C R U D
void create(String id, String pw);
User read(String id);
void update(User user);
void delete(String id);
}
service>
s-1. TodoService.java
s-2. UserService.java
s-1.
package com.example.myhttpconnection.service;
import com.example.myhttpconnection.repository.TodoRepository;
public class TodoService implements TodoRepository {
@Override
public void create() {
}
@Override
public void read() {
}
@Override
public void update() {
}
@Override
public void delete() {
}
}
s-2.
package com.example.myhttpconnection.service;
import android.util.Log;
import com.example.myhttpconnection.models.User;
import com.example.myhttpconnection.repository.UserRepository;
import com.example.myhttpconnection.utils.HttpClient2;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
public class UserService implements UserRepository {
private User user;
@Override
public void create(String id, String pw) {
}
@Override
public User read(String id) {
new Thread(() -> {
HttpURLConnection conn = HttpClient2.getInstance().getConnection("/users/" + id, HttpClient2.GET);
try {
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
user = new Gson().fromJson(reader, User.class);
Log.d("TAG", user.toString());
} else {
Log.d("TAG", "연결실패 또는 오류");
Log.d("TAG", "status code : " + conn.getResponseCode());
}
} catch (IOException e) {
e.printStackTrace();
}
try {
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
return user;
}
@Override
public void update(User user) {
}
@Override
public void delete(String id) {
}
}
utils>
u-1. HttpClient.java
u-2. HttpClient2.java
u-1.
package com.example.myhttpconnection.utils;
import android.util.Log;
import com.example.myhttpconnection.models.request.ReqPost;
import com.example.myhttpconnection.models.response.ResPost;
import com.example.myhttpconnection.models.response.ResTodo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class HttpClient {
private static HttpClient httpClient;
private static final String baseURL = "https://jsonplaceholder.typicode.com";
private HttpURLConnection conn;
public final static String GET = "GET";
public final static String POST = "POST";
public final static String PUT = "PUT";
public final static String DELETE = "DELETE";
// 싱글톤 패턴
private HttpClient() {
}
public static HttpClient getInstance() {
if (httpClient == null) {
httpClient = new HttpClient();
}
return httpClient;
}
// todos
public ArrayList<ResTodo> todos(String path) throws Exception {
ArrayList<ResTodo> resTodos = new ArrayList<>();
URL url = new URL(baseURL + path);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(GET);
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
Type listType = new TypeToken<ArrayList<ResTodo>>() {
}.getType();
resTodos = new Gson().fromJson(reader, listType);
}
conn.disconnect();
return resTodos;
}
public void posts(String path) throws Exception {
URL url = new URL(baseURL + path);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(POST);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoInput(true);
conn.setDoInput(true);
conn.setConnectTimeout(3000);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
ReqPost reqPost = new ReqPost("하이", "응답확인", 1);
String jsonObject = new Gson().toJson(reqPost);
writer.write(jsonObject);
writer.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
ResPost resPost = new Gson().fromJson(reader, ResPost.class);
Log.d("TAG", resPost.toString());
Log.d("TAG", conn.getResponseCode() + "");
conn.disconnect();
}
}
u-2.
package com.example.myhttpconnection.utils;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpClient2 {
private static HttpClient2 httpClient2;
private static final String baseURL = "https://jsonplaceholder.typicode.com";
private HttpURLConnection conn;
public final static String GET = "GET";
public final static String POST = "POST";
public final static String PUT = "PUT";
public final static String DELETE = "DELETE";
private HttpClient2() {
}
public static HttpClient2 getInstance() {
if (httpClient2 == null) {
httpClient2 = new HttpClient2();
}
return httpClient2;
}
public HttpURLConnection getConnection(String endPoint, String method) {
try {
URL url = new URL(baseURL + endPoint);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}
}
'코리아 IT아카데미 > android' 카테고리의 다른 글
15일차 | 지금까지 한 것 다 합한 예제 (0) | 2022.03.07 |
---|---|
14일차 | 레트로핏 사용 (http 통신을 할 수 있도록 도와주는) (0) | 2022.03.04 |
12일차 | Material Design tabBar/toolBar, 자주 쓰는 레이아웃, API 통신하기를 위한 http 기본개념 (0) | 2022.03.02 |
11일차 | RecyclerView, Observer(callback) (0) | 2022.02.28 |
10일차 | ListView (0) | 2022.02.28 |