zoukankan      html  css  js  c++  java
  • http请求工具类

    简单的http请求,短连接,请求完成之后就结束了,

    
    import org.apache.commons.codec.digest.DigestUtils;
    import org.apache.http.*;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.HttpUriRequest;
    import org.apache.http.client.methods.RequestBuilder;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.entity.mime.FormBodyPart;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.protocol.HTTP;
    import org.apache.http.util.EntityUtils;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.HttpURLConnection;
    import java.net.URI;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.nio.charset.Charset;
    import java.util.*;
    import java.util.Map.Entry;
    
    /**
     * @author rdd 2018.03.13
     */
    public class HttpUtils {
    
        public static final String charset = "utf-8";
    
        public static final int JS_TIME_OUT = 6000;
    
        /**
         * 不带参数的post请求,用的很少
         *
         * @param myURL
         * @return
         */
        public static String doPostUrl(String myURL) {
            URL url;
            try {
                url = new URL(myURL);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(JS_TIME_OUT);
                conn.setReadTimeout(JS_TIME_OUT);
                conn.setRequestMethod("POST");// 提交模式
                // 是否允许输入输出
                conn.setDoInput(true);
                conn.setDoOutput(true);
                // 设置请求头里面的数据,以下设置用于解决http请求code415的问题
                conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
                // 链接地址
                conn.connect();
                OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                // 发送参数
                // 清理当前编辑器的左右缓冲区,并使缓冲区数据写入基础流
                writer.flush();
                int code = conn.getResponseCode();
                BufferedReader reader = null;
                if (code == 200) {
    //                is = conn.getInputStream(); // 得到网络返回的输入流
                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                } else {
    //                is = conn.getErrorStream(); // 得到网络返回的输入流
                    reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
                }
    //            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String lines = reader.readLine();
                reader.close();
                return lines;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        private static String getSortURL(TreeMap<String, Object> mp, String head) {
            try {
                String url = "";
                Iterator<String> it = mp.keySet().iterator();
                StringBuffer sb = new StringBuffer();
                while (it.hasNext()) {
                    Object key = it.next();
                    url = url + key + "=" + URLEncoder.encode(mp.get(key).toString(), charset) + "&";
                    sb.append("|").append(mp.get(key));
                }
                return head + "?" + url;
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }
    
        private static String postForm(String reqURL, TreeMap<String, Object> params) {
            CloseableHttpClient httpclient = HttpClients.custom().build();
            try {
                RequestBuilder builder = RequestBuilder.post(reqURL);
                builder.setCharset(Charset.forName(charset));
                MultipartEntity httpEntity = new MultipartEntity();
                if (params != null) {
                    for (Entry<String, Object> entry : params.entrySet()) {
                        FormBodyPart formBodyPart = new FormBodyPart(entry.getKey(),
                                new StringBody(String.valueOf(entry.getValue()), "text/plain", Charset.forName(charset)));
                        httpEntity.addPart(formBodyPart);
                    }
                }
                builder.setEntity(httpEntity);
                HttpUriRequest post = builder.build();
                CloseableHttpResponse response = httpclient.execute(post);
                try {
                    HttpEntity entity = response.getEntity();
                    Charset respCharset = ContentType.getOrDefault(entity).withCharset(charset).getCharset();
                    String result = EntityUtils.toString(entity, respCharset);
                    EntityUtils.consume(entity);
                    return result;
                } finally {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    httpclient.close();
                } catch (IOException e) {
                }
            }
            return null;
        }
    
        private static String getMD5(String str) {
            try {
                return DigestUtils.md5Hex(str);
            } catch (Exception e) {
                throw new RuntimeException("MD5加密出现错误");
            }
        }
    
    
        /**
         * post请求(用于key-value格式的参数)
         *
         * @param url
         * @param params
         * @return
         */
        public static String doPost(String url, Map params) {
            BufferedReader in = null;
            try {
                // 定义HttpClient
                HttpClient client = new DefaultHttpClient();
                // 实例化HTTP方法
                HttpPost request = new HttpPost();
                request.setURI(new URI(url));
                //设置参数
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
                    String name = (String) iter.next();
                    String value = String.valueOf(params.get(name));
                    nvps.add(new BasicNameValuePair(name, value));
    
                    //System.out.println(name +"-"+value);
                }
                request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    
                HttpResponse response = client.execute(request);
                int code = response.getStatusLine().getStatusCode();
                if (code == 200) {    //请求成功
                    in = new BufferedReader(new InputStreamReader(response.getEntity()
                            .getContent(), "utf-8"));
                    StringBuffer sb = new StringBuffer("");
                    String line = "";
                    String NL = System.getProperty("line.separator");
                    while ((line = in.readLine()) != null) {
                        sb.append(line + NL);
                    }
    
                    in.close();
    
                    return sb.toString();
                } else {    //
                    System.out.println("状态码:" + code);
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
    
                return null;
            }
        }
    
        /**
         * post请求(用于请求json格式的参数)
         *
         * @param url
         * @param params
         * @return
         */
        public static String doPost(String url, String params) throws Exception {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);// 创建httpPost
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json");
            String charSet = "UTF-8";
            StringEntity entity = new StringEntity(params, charSet);
            httpPost.setEntity(entity);
            CloseableHttpResponse response = null;
            try {
                response = httpclient.execute(httpPost);
                StatusLine status = response.getStatusLine();
                int state = status.getStatusCode();
                if (state == HttpStatus.SC_OK) {
                    HttpEntity responseEntity = response.getEntity();
                    String jsonString = EntityUtils.toString(responseEntity);
                    return jsonString;
                } else {
    //                logger.error("请求返回:"+state+"("+url+")");
                }
            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
    }
    

    有时候请求使用长连接的话更加省资源,长连接请求.长连接工具类

    世界上所有的不公平都是由于当事人能力不足造成的.
  • 相关阅读:
    静态变量的问题
    水晶报表动态表数据显示的问题
    USACO Section 1.1 : Friday the Thirteenth
    USACO Section 1.2 : Transformations
    USACO Section 1.1 : Programming Contest Problem Types
    USACO Section 1.2 : Milking Cows
    USACO Section 1.1 : Greedy Gift Givers
    USACO Section 1.1 : Your Ride Is Here
    USACO Section 1.1 : Broken Necklace
    舍入Table.TransformColumns(Power Query 之 M 语言)
  • 原文地址:https://www.cnblogs.com/javayida/p/13347100.html
Copyright © 2011-2022 走看看