AsyncCallback.java 1.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (c) 2019-2029, Dreamlu (596392912@qq.com & www.dreamlu.net).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17
package net.dreamlu.mica.http;
18 19 20 21 22

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

23
import javax.annotation.ParametersAreNonnullByDefault;
24 25 26 27 28 29 30
import java.io.IOException;

/**
 * 异步处理
 *
 * @author L.cm
 */
31
@ParametersAreNonnullByDefault
32
public class AsyncCallback implements Callback {
33
	private final AsyncExchange exchange;
34

35 36
	AsyncCallback(AsyncExchange exchange) {
		this.exchange = exchange;
37 38
	}

39 40
	@Override
	public void onFailure(Call call, IOException e) {
41
		exchange.onFailure(call.request(), new HttpException(e));
42 43 44 45
	}

	@Override
	public void onResponse(Call call, Response response) throws IOException {
46
		try (HttpResponse httpResponse = new HttpResponse(response)) {
47
			exchange.onResponse(httpResponse);
48
			if (response.isSuccessful()) {
49
				exchange.onSuccessful(httpResponse);
50
			} else {
51
				exchange.onFailure(call.request(), new HttpException(httpResponse));
52
			}
53
		}
54 55 56
	}

}