private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
}
String id = edtId.getText().toString();
String name = edtName.getText().toString();
String passwd = edtPasswd.getText().toString();
String confirmPasswd = edtConfirmPasswd.getText().toString();
String token = FirebaseInstanceId.getInstance().getToken();


MultipartBody.Part body = null;
if (FilePath != null) {
File file = new File(FilePath);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
body = MultipartBody.Part.createFormData("PHOTO1", file.getName(), requestFile);
}

RequestBody uid = createPartFromString(PropertyManager.getInstance().getId());
RequestBody uname = createPartFromString(name);
RequestBody upass = createPartFromString(passwd);
RequestBody utoken = createPartFromString(token);


HashMap<String, RequestBody> map = new HashMap<>();
map.put("id", uid);
map.put("name", uname);
map.put("passwd", upass);
map.put("token", utoken);





'안드로이드 > Retrofit 2' 카테고리의 다른 글

Retrofit2  (0) 2017.04.05

RESTAPI를 이용해서 데이터를 가져올때 JSON을 내가 원하는 데이터로 수정하는

파싱작업의 귀찮음을 최소화할수있고, 네트워크 비동기, 동기 통신 또한 

매우 편하고 깔끔하게 구현 할 수 있도록 다양한 메소드를 제공한다.




인터넷 통신을 하기 위해 퍼미션을 추가

<uses-permission android:name="android.permission.INTERNET"/>



Retrofit 2 추가

build.gradle 파일에 아래와 같이 Retrofit 2를 추가합니다.

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'




public class RetrofitCreator {

private static final String SERVER = "http://xxx";

public static Retrofit createRetrofit() {

return new Retrofit.Builder()
.baseUrl(SERVER)
.addConverterFactory(GsonConverterFactory.create())
.build();

}
}

baseUrl의 요청하는 서버의 도메인이나, IP:PORT 정보를 입력해주고, 

addConverterFactory 메소드로 Response 데이터의 파싱을 담당할 객체를 생성해준다.

GSON을 이용하여 JSON 파싱을 했기 떄문에, 위와 같이 작성





인터페이스 class 만들기


요청 메소드

모든 메소드들은 반드시 상대 URL과 요청 메소드를 명시하는 어노테이션을 가지고 있어야합니다. 기본으로 제공하는 요청 메소드 어노테이션은 다음과 같이 5개가 있습니다 : GET, POST, PUT, DELETE, HEAD.


@FormUrlEncoded 어노테이션을 메소드에 명시하면 form-encoded 데이터로 전송 됩니다. 각 key-value pair의 key는 어노테이션 값에, value는 객체를 지시하는 @Field 어노테이션으로 매개변수에 명시하시면 됩니다.


Multipart 요청은 @Multipart 어노테이션을 메소드에 명시하시면 됩니다. 각 파트들은 @Part 어노테이션으로 명시합니다.

Multipart의 part는 Retrofit 의 컨버터나, RequestBody 를 통하여 직렬화(serialization) 가능한 객체를 사용하실 수 있습니다.

interface Api {
//회원가입
@FormUrlEncoded
@POST("/mobile/signup.php")
Call<ServerResponse> signUp(
@Field("id") String id,
@Field("name") String name,
@Field("passwd") String passwd,
@Field("token") String token,
);

//회원정보수정
@Multipart
@POST("/mobile/signmodfiy.php")
Call<ServerResponse> signModify(
@PartMap() Map<String, RequestBody> partMap,
@Part MultipartBody.Part body

);





public class ChatApi {

private static ChatApi.Api api;

private static ChatApi instance;

private ChatApi () {
Retrofit retrofit = RetrofitCreator.createRetrofit();
api = retrofit.create(Api.class);
}

public static ChatApi getInstance () {
if ( instance == null ) {
instance = new ChatApi();
}

return instance;
}

//회원가입
public Call<ServerResponse> signUp(String id, String name, String passwd,String token ) {

return api.signUp(id, name, passwd, token);
}

//회원정보수정
public Call<ServerResponse> signModify(MultipartBody.Part body, Map<String, RequestBody> partMap) {
return api.signModify(partMap, body);
}

retrofit의 구현체에게 인터페이스의 class 정보를 보내준다






public class ServerResponse {

private int success;
private String message;

public int getSuccess() {
return success;
}

public String getMessage() {
return message;
}
}

요청결과를 파싱할 모델 클래스





chatApi.signUp(id, name, passwd, token).enqueue(new Callback<ServerResponse>() {
@Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {

if (response.body().getSuccess() == 1) {

}
}

@Override
public void onFailure(Call<ServerResponse> call, Throwable t) {

}
});

서비스의 인터페이스에 서술해뒀던, 메소드를 호출하면서, 파라메터만 넘겨준다.

'안드로이드 > Retrofit 2' 카테고리의 다른 글

Retrofit2 파일업로드  (0) 2017.04.05

+ Recent posts