OkHTTP 기본 사용

6332 단어 게임 개발
GET 요청private void okHttpget(String URL) {//client 객체 만들기 OkHttpClient = new OkHttpClient.Builder()//연결 시간 설정.callTimeout(5, TimeUnit.SECONDS)//읽기 시간 설정.readTimeout(5, TimeUnit.SECONDS)//OkHttpClient 객체 만들기.build();
    //request 
    Request request = new Request.Builder()
            // url
            .url(url)
            // 
            .get()
            // request 
            .build();
    // 
    Call call = client.newCall(request);

    // 
    call.enqueue(new Callback() {
        // 
        @Override
        public void onFailure(Call call, IOException e) {

        }

        // 
        @Override
        public void onResponse(Call call,  Response response) throws IOException {

            Log.i("##", "onResponse: "+response.body().string());
        }
    });
}

POST는 private void okHttpPost Register(String url, String name, String params) {OkHttp Client client = new OkHttp Client. Builder ().read Timeout (5, Time Unit.SECONDS).call Timeout (5, Time Unit.SECONDS).build () 를 요청합니다.
    // RequsetBody 
    FormBody formBody = new FormBody.Builder()
            .add("phone", phone)
            .build();

    Request request = new Request.Builder()
            .url(url)
            .post(formBody)
            .build();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.i("##", "onResponse: "+response.body().string());
        }
    });
}

단순히 패키지된 OkHttp 도구 클래스 OkHttpUtil 클래스 import com.example.h0804_day03okhttp.model.OkHttpListener;
import java.io.IOException; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit;
import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response;
public class OkHttpUtil { private OkHttpClient client;
// client  
private OkHttpUtil() {
    client = new OkHttpClient.Builder()
            .callTimeout(5, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.SECONDS)
            .build();
}


// 
private static OkHttpUtil instance;

public static OkHttpUtil getInstance() {
    if (instance == null) {
        synchronized (OkHttpUtil.class) {
            if (instance == null) {
                instance = new OkHttpUtil();
            }
        }
    }
    return instance;
}

/***
 *
 * @param url  
 * @param listener  
 */
public void okHttpGet(String url, final OkHttpListener listener) {
    Request request = new Request.Builder()
            .url(url)
            .get()
            .build();

    Call call = client.newCall(request);

    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            listener.fail(e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            listener.success(response.body().string());
        }
    });
}

/***
 *
 * @param url  
 * @param map  
 * @param listener  
 */
public void okHttpPost(String url, Map map, final OkHttpListener listener) {
    FormBody.Builder formBodyBuilder = new FormBody.Builder();

    Set keySet = map.keySet();
    for (String key : keySet) {
        formBodyBuilder.add(key, map.get(key));
    }

    FormBody formBody = formBodyBuilder.build();

    Request request = new Request.Builder()
            .url(url)
            .post(formBody)
            .build();

    Call call = client.newCall(request);

    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            listener.fail(e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            listener.success(response.body().string());
        }
    });
}

}
/***
 * 
 * @param url  
 * @param file  
 * @param listener  
 */
public void okHttpDownload(String url, final String file, final OkHttpListener listener) {

    Request request = new Request.Builder()
            .url(url)
            .get()
            .build();

    Call call = client.newCall(request);

    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            listener.fail(e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            // 
            InputStream is = response.body().byteStream();
            FileOutputStream fos = new FileOutputStream(file);
            int length = 0;
            byte[] bytes = new byte[1024 * 8];

            // 
            while ((length = is.read(bytes)) != -1){
                fos.write(bytes,0,length);
            }
            if (is != null) {
                is.close();
            }
            if (fos != null) {
                raf.close();
            }
            listener.success(" ");
        }
    });

}

/**** @param url 서버 주소* @param filePath 파일을 업로드할 경로 * @param fileName 파일을 서버에 업로드한 다음 이름 * @param type 파일 유형 * @param listener 인터페이스 리셋 결과 */public void okHttp Upload (String url, String filePath, String fileName, String type, final OkHttp Listener listener)
    MultipartBody multipartBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", fileName, RequestBody.create(MediaType.parse(type), new File(filePath)))
            .build();

    Request request = new Request.Builder()
            .url(url)
            .post(multipartBody)
            .build();

    Call call = client.newCall(request);

    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            listener.fail(e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            listener.success(" ");
        }
    });

좋은 웹페이지 즐겨찾기