안드로이드 스튜디오 AndroidManifest.xml
설정
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
...
android:usesCleartextTraffic="true">
build.gradle
에 Retrofit , okhttp3 추가
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation com.squareup.retrofit2:converter-scalars:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
서버와 통신할 메소드들이 담긴 인터페이스를 만들어 준다
import java.util.Map;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
public interface OcrFactory {
@GET("ocr/connect") // <=요기 안에 들어가는게 서버 path
Call<String> connect(@Query("userEmail") String email);
@GET("ocr/connecting") // <=요기 안에 들어가는게 서버 path
Call<Semester> connecting(@QueryMap Map<String, String> success);
@POST("ocr/semester") // <=요기 안에 들어가는게 서버 path
Call<Res_semester> semester(@Body Req_semester user);
}
인터페이스에서 통신 부분에서 대부분의 메소드들을 다 넣을수록 깔끔.
또는 기능별로 나누어 인터페이스 분류 하기.
하나의 서버와 통신을 담당하는 하나의 Singletone 클래스 만들기
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public class Net {
private static Net ourinstance = new Net();
public static Net getInstance(){
return ourinstance;
}
Gson gson = new GsonBuilder().setLenient().create();
private Net(){
}
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor()).build();
private Retrofit retrofit = new Retrofit.Builder()
.baseUrl("") //<= 서버 주소값 입력
.client(client) //<= OkHttpClient 연동
.addConverterFactory(ScalarsConverterFactory.create()) //<= 고질적인 에러 :JSON document was not fully consumed 해결
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
OcrFactory ocrFactory;
public OcrFactory getOcrFactory(){
if(ocrFactory == null){
ocrFactory = retrofit.create(OcrFactory.class);
}
return ocrFactory;
}
private HttpLoggingInterceptor httpLoggingInterceptor(){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
android.util.Log.e("MyLogis :", message + "");
}
});
return interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
}
}
학기 시간표 데이터를 담는 Semester 클래스 작성
public class Semester {
private String major1,major2;
private String Class1,Class2,Class3,Class4,Class5;
public Semester(){
}
@Override
public String toString(){
return "semester{" +
"major1='" + major1 + '\'' +
", major2=" + major2 +
", Class1='" + Class1 + '\'' +
", Class2='" + Class2 + '\'' +
", Class3='" + Class3 + '\'' +
", Class4='" + Class4 + '\'' +
", Class5='" + Class5 + '\'' +
'}';
}
public Semester(String major1, String major2, String Class1, String Class2, String Class3, String Class4, String Class5){
this.major1= major1;
this.major2 = major2;
this.Class1 = Class1;
this.Class2 = Class2;
this.Class3 = Class3;
this.Class4 = Class4;
this.Class5 = Class5;
}
public String getClass1() {
return Class1;
}
public void setClass1(String class1) {
Class1 = class1;
}
public String getClass2() {
return Class2;
}
public void setClass2(String class2) {
Class2 = class2;
}
public String getClass3() {
return Class3;
}
public void setClass3(String class3) {
Class3 = class3;
}
public String getClass4() {
return Class4;
}
public void setClass4(String class4) {
Class4 = class4;
}
public String getClass5() {
return Class5;
}
public void setClass5(String class5) {
Class5 = class5;
}
public String getMajor1() {
return major1;
}
public void setMajor1(String major1) {
this.major1 = major1;
}
public String getMajor2() {
return major2;
}
public void setMajor2(String major2) {
this.major2 = major2;
}
}
pojo 사이트를 통해 빠르게 만들수 있다
액티비티에서 Retrofit 사용방법
connect 함수(GET, Res = String, Req = String )
Call<String> res = Net.getInstance().getOcrFactory().connect("bangjinhyuk");
res.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
if(response.body() != null){
String success = response.body().toString();
Log.d("Main 통신", response.body().toString());
}else{
Log.e("Main 통신", "실패 1 response 내용이 없음");
}
}else{
Log.e("Main 통신", "실패 2 서버 에러");
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("Main 통신", "실패 3 통신 에러 "+t.getLocalizedMessage());
}
});
connecting 함수 (GET, Res = String, Req = Map )
Map<String, String> map = new HashMap<String, String>();
map.put("name","bbangi");
map.put("birth", "0103");
Call<Semester> res1 = Net.getInstance().getOcrFactory().connecting(map);
res1.enqueue(new Callback<Semester>() {
@Override
public void onResponse(Call<Semester> call, Response<Semester> response) {
if(response.isSuccessful()){
if(response.body() != null){
Semester semesters = response.body();
Log.d("Map 통신", semesters.toString());
}else{
Log.e("Map 통신", "실패 1 response 내용이 없음");
}
}else{
Log.e("Map 통신", "실패 2 서버 에러");
}
}
@Override
public void onFailure(Call<Semester> call, Throwable t) {
Log.e("Map 통신", "실패 3 통신 에러 "+t.getLocalizedMessage());
}
});
semester 함수 (POST, Res = Res_semester, Req = Req_semester)
Req_semester req_semester = new Req_semester();
req_semester.setSemester(new Semester(
"소프트웨어학과",
"미디어학과",
"컴구",
"창소입",
"기창경",
"",
""
));
Call<Res_semester> res2 = Net.getInstance().getOcrFactory().semester(req_semester);
res2.enqueue(new Callback<Res_semester>() {
@Override
public void onResponse(Call<Res_semester> call, Response<Res_semester> response) {
if(response.isSuccessful()) {
if (response.body() != null) {
Res_semester res_semester = response.body();
Log.d("semester 통신",res_semester.code+"");
} else {
Log.e("semester 통신", "실패 1 response 내용이 없음");
}
}else{
Log.e("semester 통신", "실패 2 서버 에러");
}
}
@Override
public void onFailure(Call<Res_semester> call, Throwable t) {
Log.e("semester 통신", "실패 3 통신 에러 "+t.getLocalizedMessage());
}
});
```
Req,Res 클래스
class Res_semester {
int code; //서버로부터의 응답 코드. 404, 500, 200 등.
String msg; //서버로부터의 응답 메세지.
Semester semester; //공부필요.
}
class Req_semester {
Semester semester;
public Semester getSemester() {
return semester;
}
public void setSemester(Semester semester) {
this.semester = semester;
}
}
```
ocr.js
파일 작성 var express = require('express');
var router = express.Router();
/* GET ocr listing. */
router.get('/connect', function(req, res, next) {
if(req.query.userEmail == 'bangjinhyuk'){
res.send('connect all sucess');
}else{
res.send('connect little sucess');
}
});
/* GET ocr listing. */
router.get('/connecting', function(req, res, next) {
if(req.query.name == 'bbangi' && req.query.birth == '0103'){
res.send(JSON.stringify(
{"major1":"소웨",
"major2": "미디어",
"Class1":"1",
"Class2":"2",
"Class3":"3",
"Class4":"4",
"Class5":"5"}));
}else{
res.send('connecting little sucess');
}
});
/* GET ocr listing. */
router.post('/semester', function(req, res, next) {
res.send('{"code":-1, "msg": "failed"}');
// if(req.body.semester == 'bbangi' && req.query.birth == '0103' ){
// res.send('connecting all sucess');
// }else{
// res.send('connecting little sucess');
// }
});
/* GET ocr listing. */
router.get('/', function(req, res, next) {
// res.send(req.body.userEmail);
res.send('connect');
});
module.exports = router;