HttpUtil工具类

代码:


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

public class HttpUtils {
    static Logger logger = Logger.getLogger(HttpUtils.class);

    public static JSONObject httpGet(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "text/json;charset=utf-8");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        StringBuffer buf = new StringBuffer();
        String inputLine = in.readLine();
        while (inputLine != null) {
            buf.append(inputLine).append("\r\n");
            inputLine = in.readLine();
        }
        in.close();
        //
        return new JSONObject(buf.toString().trim());
    }

    public static String httpGet1(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "text/json;charset=utf-8");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        StringBuffer buf = new StringBuffer();
        String inputLine = in.readLine();
        while (inputLine != null) {
            buf.append(inputLine).append("\r\n");
            inputLine = in.readLine();
        }
        in.close();
        //
        return buf.toString().trim();
    }

    public static String httpGet2(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        StringBuffer buf = new StringBuffer();
        String inputLine = in.readLine();
        while (inputLine != null) {
            buf.append(inputLine).append("\r\n");
            inputLine = in.readLine();
        }
        in.close();
        //
        return buf.toString().trim();
    }

    public static String httpPut(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        int code = conn.getResponseCode();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        logger.error("code=" + conn.getResponseCode());
        StringBuffer buf = new StringBuffer();
        String inputLine = in.readLine();
        while (inputLine != null) {
            buf.append(inputLine).append("\r\n");
            inputLine = in.readLine();
        }
        in.close();
        //
        return (buf.toString().trim()) != null ? (buf.toString().trim()) : (code + "");
    }

    public static JSONObject httpPost(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "text/json;charset=utf-8");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        StringBuffer buf = new StringBuffer();
        String inputLine = in.readLine();
        while (inputLine != null) {
            buf.append(inputLine).append("\r\n");
            inputLine = in.readLine();
        }
        in.close();
        //
        return new JSONObject(buf.toString().trim());
    }

    public static JSONObject httpPost(String urlStr, String postText) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        byte[] bytes = postText.getBytes("utf-8");
        OutputStream os = conn.getOutputStream();
        os.write(bytes);
        os.close();
        //
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        StringBuffer buf = new StringBuffer();
        String inputLine = in.readLine();
        while (inputLine != null) {
            buf.append(inputLine).append("\r\n");
            //
            inputLine = in.readLine();
        }
        in.close();
        //
        return new JSONObject(buf.toString().trim());
    }

    public static Object post(List<NameValuePair> message, String to)
            throws ParseException, IOException, JSONException {

        HttpPost post = new HttpPost(to);
        UrlEncodedFormEntity params = new UrlEncodedFormEntity(message, "UTF-8");
        post.setEntity(params);
        System.out.println(("[] Post \"" + message + "\" to " + post.getURI()));
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("[] Server Status Code: " + statusCode);

        String respString = null;
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            respString = EntityUtils.toString(entity, "UTF-8");
        }
        System.out.println("[] Server return: " + respString);
        EntityUtils.consume(entity);

        JSONObject result = new JSONObject(respString.trim());
        if (result != null && result.has("success") && result.opt("success").equals("true")) {
            return result.opt("data");
        } else {
            logger.info(message);
            return "error";
        }
    }

    public static String httpPostApplication(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        StringBuffer buf = new StringBuffer();
        String inputLine = in.readLine();
        while (inputLine != null) {
            buf.append(inputLine).append("\r\n");
            inputLine = in.readLine();
        }
        in.close();
        //
        return buf.toString().trim();
    }

    public static String RestfulGet(String url) {
        String returnString = "";
        try {
            URL restServiceURL = new URL(url);
            HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setRequestProperty("Accept", "application/json");
            httpConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpConnection.setRequestProperty("contentType", "utf-8");
            if (httpConnection.getResponseCode() != 200) {
                throw new RuntimeException(
                        "HTTP GET Request Failed with Error code : " + httpConnection.getResponseCode());
            }
            BufferedReader responseBuffer = new BufferedReader(
                    new InputStreamReader((httpConnection.getInputStream()), "utf-8"));
            String output = responseBuffer.readLine();
            // System.out.println("Output from Server: \n");
            StringBuffer buf = new StringBuffer();
            while (output != null) {
                buf.append(output).append("\r\n");
                output = responseBuffer.readLine();
            }
            responseBuffer.close();
            httpConnection.disconnect();
            returnString = buf.toString().trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnString;
    }

    public static String RestfulPost(String url, String input) {
        String result = "";
        try {
            URL targetUrl = new URL(url);
            HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
            httpConnection.setDoOutput(true);
            httpConnection.setRequestMethod("POST");
            httpConnection.setRequestProperty("Charsert", "UTF-8");
            httpConnection.setRequestProperty("Content-Type", "application/json");
            OutputStream outputStream = httpConnection.getOutputStream();
            outputStream.write(input.getBytes());
            outputStream.flush();
            if (httpConnection.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + httpConnection.getResponseCode());
            }
            BufferedReader responseBuffer = new BufferedReader(
                    new InputStreamReader((httpConnection.getInputStream()), "UTF-8"));
            String output;
            System.out.println("Output from Server:\n");
            StringBuffer buf = new StringBuffer();
            while ((output = responseBuffer.readLine()) != null) {
                buf.append(output).append("\r\n");
            }
            httpConnection.disconnect();
            responseBuffer.close();
            result = buf.toString().trim();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;

    }

    public static org.codehaus.jettison.json.JSONObject post(net.sf.json.JSONObject json, String to)
            throws ParseException, IOException, JSONException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(to);
        post.setHeader("Content-Type", "application/json");
        org.codehaus.jettison.json.JSONObject result = null;
        java.io.InputStream inStream = null;
        try {
            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(s);
            // 发送请求
            HttpResponse httpResponse = client.execute(post);
            // 获取响应输入流
            inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                strber.append(line + "\n");
            }
            inStream.close();
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                result = new org.codehaus.jettison.json.JSONObject(strber.toString());
            } else {
                logger.error("请求服务端失败" + json);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static net.sf.json.JSONObject doPutOrPost(String type, String urlString, net.sf.json.JSONObject jsonObject,
            String callMethed) {
        try {
            String result = "";
            String info = callMethed + ",调用SDK的restful接口URL:" + urlString + ",请求参数:" + jsonObject.toString() + ",请求方式:"
                    + type;
            logger.info(info);
            URL url = new URL(urlString);
            int code = 0;
            // 打开restful链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 提交模式
            conn.setRequestMethod(type);
            conn.setConnectTimeout(200000);// 连接超时 单位毫秒
            conn.setReadTimeout(200000);// 读取超时 单位毫秒
            conn.setDoOutput(true);// 是否输入参数
            conn.setDoInput(true);
            // 设置访问提交模式,表单提交
            conn.setRequestProperty("Content-Type", "application/json");
            // 设置请求头
            // conn.setRequestProperty(SDKKeyName, SDKKey);
            // conn.setRequestProperty(SDKValueName, SDKValue);
            // ----------------传入数据----------------------
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(jsonObject.toString().getBytes());
            code = conn.getResponseCode();
            outputStream.flush();
            // 判断是否创建成功
            logger.info(info + ",调用所得code值为:" + code);
            System.out.println("---------code=" + code);
            if (code == 200) {// 执行成功
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                reader.close();
                result = buffer.toString();
                logger.info(info + ",调用结果信息为:" + result);
                net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(result);
                return jsonObj;
            } else {
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "utf-8"));
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                reader.close();
                result = buffer.toString();
                logger.info(info + ",调用结果信息为:" + result);
                net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(result);
                return jsonObj;

            }
        } catch (Exception e) {
            logger.error("请求失败", e);
            return null;
        }
    }

    public static int intOf(Object obj, int initValue) {
        // 1.判断参数是否合法
        if (obj == null || "".equals(obj)) {
            return initValue;
        } else {
            try {
                return Integer.parseInt(obj.toString());
            } catch (Exception e) {
                e.getMessage();
                return initValue;
            }
        }
    }
}

 

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
httputil是一个常用的网络请求工具类,用于发送HTTP请求并获取响应。在使用httputil工具类发送请求时,可以通过设置请求的cookie来实现身份验证、会话管理等功能。 要设置cookie,首先需要创建一个HttpClient对象。HttpClient用于发送请求并获取响应。在创建HttpClient对象时,可以通过HttpClientBuilder类来设置一些自定义的配置,包括cookie的相关设置。 1. 创建HttpClient对象: ```java HttpClient httpClient = HttpClientBuilder.create().build(); ``` 2. 创建HttpPostHttpGet对象,设置请求URL和其他相关参数。 3. 设置cookie: ```java CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("cookie_name", "cookie_value"); cookie.setDomain("example.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); ``` 这里创建了一个CookieStore对象,用于存储cookie。然后创建一个BasicClientCookie对象,设置cookie的名称和值。可以通过setDomain()和setPath()方法设置cookie的域和路径。将cookie添加到cookieStore中。 然后创建一个HttpContext对象,并将cookieStore设置为其属性。将HttpContext对象传递给HttpClient对象的execute()方法,执行请求。 4. 发送请求: ```java HttpResponse response = httpClient.execute(httpPost, httpContext); ``` 通过以上步骤,就可以使用httputil工具类发送带有cookie的HTTP请求了。在发送请求时,服务器将根据提供的cookie进行身份验证或会话管理。 需要注意的是,htttputil工具类的具体使用方式可能会因具体的框架和版本而有所不同,可以根据实际情况进行相应的调整。以上是一个基本的示例,供参考使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值