andoird HTTP 工具类
16lz
2022-05-28
简单的对android下apach包进行了封装。
import java.io.IOException;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.methods.HttpUriRequest;import org.apache.http.entity.ByteArrayEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpConnectionParams;import org.apache.http.params.HttpParams;import org.apache.http.util.EntityUtils;public final class HTTPUtils {public static byte[] postToServer(String url, byte[] content)throws ClientProtocolException, IOException {return executeRequest(url, new ByteArrayEntity(content),HttpPost.METHOD_NAME);}public static byte[] getFromServer(String url) throws ClientProtocolException, IOException {return executeRequest(url, null, HttpGet.METHOD_NAME);}private static byte[] executeRequest(String url, HttpEntity postEntity,String methodName) throws ClientProtocolException, IOException {HttpUriRequest request = null;HttpClient client = null;byte[] resultBytes = null;try {if (HttpPost.METHOD_NAME.equals(methodName)) {request = new HttpPost(url);if (postEntity != null) {HttpPost post = ((HttpPost) request);post.setEntity(postEntity);}} else if (HttpGet.METHOD_NAME.equals(methodName)) {request = new HttpGet(url);}client = createHttpClient();HttpResponse response = client.execute(request);int statusCode = response.getStatusLine().getStatusCode();if (statusCode == HttpStatus.SC_OK) {HttpEntity entity = response.getEntity();resultBytes = EntityUtils.toByteArray(entity);}} finally {if (request != null) {request.abort();}}return resultBytes;}private static HttpClient createHttpClient() {HttpParams httpParameters = new BasicHttpParams();int timeoutConnection = 30000;HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);int timeoutSocket = 30000;HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);return new DefaultHttpClient(httpParameters);}}
更多相关文章
- Android(安卓)封装自己的工具Jar
- android sqlite数据库封装 实现crud
- Antrus – 我搞的一个Android下的MVC开源框架
- Android下Entity封装工具类
- Android之网络请求3————OkHttp的拦截器和封装
- android 仿ios 对话框已封装成工具类
- android 仿ios 对话框已封装成工具类
- Android(安卓)Camer2与Camera1 自定义相机拍照封装实例讲解
- android倒计时封装(活动进入后台,倒计时依然能正常计时)