基于httpclient的get和post工具类

httpclient的maven地址:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

HttpRequestUtils类:

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * HTTP请求工具类
 * @author dreamof2015
 */
public class HttpRequestUtils {

    /**
     * post请求
     * @param url
     * @param jsonParam
     * @return
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        JSONObject jsonObject = new JSONObject();
        if(jsonParam!=null){
            Iterator<String> sIterator = jsonParam.keys();
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            while(sIterator.hasNext()){
                String key = sIterator.next();
                String value = jsonParam.getString(key);
                nvps.add(new BasicNameValuePair(key,value));
            }
            try {
                post.setEntity(new UrlEncodedFormEntity(nvps));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            CloseableHttpResponse response = httpclient.execute(post);
            HttpEntity entity = response.getEntity();
            jsonObject.put("status",response.getStatusLine());
            EntityUtils.consume(entity);
            jsonObject.put("responseText",entity.getContent());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * get请求
     * @param url
     * @return
     */
    public static JSONObject httpGet(String url){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        JSONObject jsonObject = new JSONObject();
        HttpGet httpGet = new HttpGet(url);
        try {
            CloseableHttpResponse response = httpclient.execute(httpGet);
            jsonObject.put("status",response.getStatusLine());
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);
            jsonObject.put("responseText",entity.getContent());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用 HttpClient 进行文件下载的工具类示例: ```java import org.apache.http.HttpEntity; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ClientConnectionManager; 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; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class FileDownloadUtil { private static final int TIMEOUT_CONNECTION = 5000; // 连接超时时间 private static final int TIMEOUT_SOCKET = 5000; // 读取超时时间 public static boolean downloadFile(String url, String filePath) { HttpClient httpClient = null; HttpGet httpGet = null; try { httpClient = getHttpClient(); httpGet = new HttpGet(url); HttpEntity httpEntity = httpClient.execute(httpGet).getEntity(); if (httpEntity != null) { FileOutputStream fos = new FileOutputStream(new File(filePath), false); fos.write(EntityUtils.toByteArray(httpEntity)); fos.flush(); fos.close(); return true; } } catch (IOException e) { e.printStackTrace(); } finally { if (httpGet != null) { httpGet.abort(); } if (httpClient != null) { ClientConnectionManager mgr = httpClient.getConnectionManager(); if (mgr != null) { mgr.shutdown(); } } } return false; } private static HttpClient getHttpClient() { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_CONNECTION); HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET); return new DefaultHttpClient(params); } } ``` 使用示例: ```java String url = "http://example.com/example.pdf"; String filePath = "/path/to/file/example.pdf"; boolean success = FileDownloadUtil.downloadFile(url, filePath); if (success) { System.out.println("文件下载成功!"); } else { System.out.println("文件下载失败!"); } ``` 需要注意的是,在使用 HttpClient 进行网络请求时,需要在 AndroidManifest.xml 文件中添加网络访问权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值