[Android] 안드로이드 HTTP요청 사용법 (GET/POST/PUT/DELETE)
들어가며
HTTP는 Server와 통신하는데 가장 modern한 방식 중 하나이다. 서버에 GET, POST, PUT, DELETE 요청을 통해 데이터를 주고 받는 방법에 대해서 설명한다. 오픈 소스인 OkHttp를 설치하고, HTTP요청 방법에 대해서 설명하겠습니다.
설치하기
설치하는 방법은 총 3가지이다. jar파일 다운 또는 Maven, Gradle 추가이다.
- v3.2.0 Jar [다운로드]
- Gradle
compile 'com.squareup.okhttp3:okhttp:3.2.0' - Maven
com.squareup.okhttp3 okhttp 3.2.0
GET
package okhttp3.guide;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class GetExample {
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public static void main(String[] args) throws IOException {
GetExample example = new GetExample();
String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
System.out.println(response);
}
}
POST, PUT, DELETE
Request의 객체를 만들때 post를 put, delete로 변경하면 POST, PUT, DELETE 요청을 할 수 있다.
package okhttp3.guide;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class PostExample {
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
String bowlingJson(String player1, String player2) {
return "{'winCondition':'HIGH_SCORE',"
+ "'name':'Bowling',"
+ "'round':4,"
+ "'lastSaved':1367702411696,"
+ "'dateStarted':1367702378785,"
+ "'players':["
+ "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
+ "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
+ "]}";
}
public static void main(String[] args) throws IOException {
PostExample example = new PostExample();
String json = example.bowlingJson("Jesse", "Jake");
String response = example.post("http://www.roundsapp.com/post", json);
System.out.println(response);
}
}
'안드로이드 > 안드로이드 TIP' 카테고리의 다른 글
[Android] 안드로이드 Intent를 이용한 파일열기 (0) | 2021.04.29 |
---|---|
[Android] 파일 삭제하기 (0) | 2021.04.29 |
[Android] 안드로이드 파일 목록 가져오기 (0) | 2021.04.29 |
[Android] 안드로이드 전체 화면 사용하기 - 상태바, 액션바 숨기기, 제거하기 (Status Bar, Action Bar Hiding/Removing) (0) | 2021.04.29 |
[Android] 안드로이드 SharedPreference 사용하기 (0) | 2021.04.28 |
[안드로이드]AsyncTask 설명 (0) | 2020.09.07 |
[안드로이드 컴포넌트] 액티비티 생애주기(The Activity Lifecycle) (0) | 2018.09.10 |
[안드로이드 컴포넌트] Service 구현 예제, 안드로이드 백그라운드 서비스, Service Example of Android Components, Android Background (0) | 2018.09.10 |