基于httpclient的get和post工具类

httpclient的maven地址:

<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpclientartifactId>
    <version>4.5.3version>
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 sIterator = jsonParam.keys();
            List nvps = new ArrayList();
            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;
    }
}

你可能感兴趣的:(java)