본문 바로가기
슬기로운 자바 개발자 생활/안드로이드 프로그래밍

Retrofit 간단한 Post로 서버에 데이터 보내기

by 슬기로운 동네 형 2016. 4. 20.
반응형


first_name 과 last_name을 안드로이드로 부터 값을 받는 예제

1.스프링부트 서버 코딩

@RestController
@RequestMapping("/api/")
public class ApiControll {

private static final Logger logger = LoggerFactory.getLogger(ApiControll.class);

@RequestMapping(value= "expost",method= RequestMethod.POST)
public Message TestPost(HttpServletRequest request) {

Message m = new Message();

try{

m.setMsg("정상적으로 서버에서 값을 받음");
String first_name = request.getParameter("first_name");
String last_name = request.getParameter("last_name");
logger.info("첫번째 이름 : "+ first_name);
logger.info("두번째 이름 : "+ last_name);
return m;

}catch (Exception e){

m.setMsg("서버에서 값을 받는 도중 문제가 생겼습니다");
e.printStackTrace();
return m;
}
}

class Message{
String msg;

Message(){}

public Message(String msg) {
this.msg = msg;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}
}

2. 안드로이드 XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
android:id="@+id/first_name"
android:hint="first_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignLeft="@+id/last_name"
android:layout_alignStart="@+id/last_name"
android:layout_alignRight="@+id/last_name"
android:layout_alignEnd="@+id/last_name" />

<EditText
android:id="@+id/last_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:layout_below="@+id/first_name"
android:hint="last_name"
android:layout_centerHorizontal="true" />

<Button
android:id="@+id/btn_send"
android:text="서버로 전송"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/last_name"
android:layout_centerHorizontal="true" />


</RelativeLayout>

3.Activity 코딩


public class PostActivity extends Activity{

public static String SERVER_ADRESS = "http://192.168.1.101:8080";

EditText first;
EditText last;
Button btnSend;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_post);

first = (EditText) findViewById(R.id.first_name);
last = (EditText) findViewById(R.id.last_name);
Button btnSend = (Button) findViewById(R.id.btn_send);

btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

String firstName = first.getText().toString();
String lastName = last.getText().toString();

final Call<Message> m = PostActivity.RetrofitServiceImplFactory.serverPost().sendName(firstName,lastName);

m.enqueue(new Callback<Message>() {
@Override
public void onResponse(Response<Message> response, Retrofit retrofit) {
final Message message = response.body();
Toast.makeText(getApplicationContext(), "서버에 값을 전달했습니다 : " + message.getMsg(), Toast.LENGTH_SHORT).show();
}

@Override
public void onFailure(Throwable t) {
t.printStackTrace();
Toast.makeText(getApplicationContext(), "서버와 통신중 에러가 발생했습니다", Toast.LENGTH_SHORT).show();
}
});
}
});
}
public interface ServerPost{
@FormUrlEncoded
@POST("/api/expost")
Call<Message> sendName(@Field("first_name") String first, @Field("last_name") String last);
}

static class RetrofitServiceImplFactory{
private static Retrofit getretrofit(){
return new Retrofit.Builder()
.baseUrl(SERVER_ADRESS)
.addConverterFactory(GsonConverterFactory.create()).build();
}

public static ServerPost serverPost(){
return getretrofit().create(ServerPost.class);
}
}
}


반응형

댓글