okhttp 사용하기

Posted by Albert 2836Day 20Hour 18Min 25Sec ago [2017-07-14]

file MainActivity.java

일단 관련앱 빌드그레이드 파일을 열어서

compile 'com.squareup.okhttp3:okhttp:3.6.0'

추가하여 okhttp적용한다.

private String getData(String url) throws IOException {
// okHTTP 인스턴스 생성
OkHttpClient client = new OkHttpClient();
// request 생성
Request request = new Request.Builder()
.url(url)
.build();
// client 인스턴스에 request 를 담아 보낸다
Response response = client.newCall(request).execute(); // -> 서버측으로 요청
return response.body().string();
}

사용시

new Thread() {
@Override
public void run() {
try {
String result = getData("http://172.20.80.100:8003/testOkhttp");
Log.i("RESULT", "result============" + result);

} catch (IOException e) {
e.printStackTrace();
}
}
}.start();

혹은

new AsyncTask<Void, Void, Void>(){
@Override
protected Void doInBackground(Void... voids) {
try {
String result = getData("http://172.20.80.100:8003/testOkhttp");
Log.i("RESULT", "result============" + result);

} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute();

요런방식으로 하면 된다.

포스트방식도 가능한데 더 상세한 사용법은 http://square.github.io/okhttp/ 

에서 확인 가능하다.




LIST

Copyright © 2014 visionboy.me All Right Reserved.