当前位置: 首页 > 工具软件 > httpkit > 使用案例 >

HttpKit--请求示例

陶锋
2023-12-01

需要下载0oky-httpkit-0.0.1.jar依赖包
1 get请求

/**
     * 发送get请求
     * 
     * @param url
     * @return
     */
    public static String doGet(String url) {
        return HttpKit.get(url).execute().getString();
    }

/**
     * 发送get请求
     * 
     * @param url
     * @param param
     * @return
     */
    public static String doGet(String url, Map<String, Object> param) {
        StringBuilder strBuildUrl = new StringBuilder();
        strBuildUrl.append(url);
        if (param != null) {
            // 构造键值对URL
            boolean isFirst = true;
            for (Entry<String, Object> entry : param.entrySet()) {
                if (isFirst) {
                    strBuildUrl.append("?");
                    strBuildUrl.append(entry.getKey()).append("=").append(entry.getValue());
                    isFirst=false;
                } else {
                    strBuildUrl.append("&");
                    strBuildUrl.append(entry.getKey()).append("=").append(entry.getValue());
                }
            }
        }
        return doGet(strBuildUrl.toString());
    }

2 post发送表单数据

/**
     * 发送表单数据
     * 
     * @param url
     * @param param
     * @return
     */
    public static String doPostForm(String url, Map<String, Object> param) {
        // 头信息
        Map<String, String> head = new HashMap<String, String>();
        head.put("accept", "*/*");
        head.put("connection", "Keep-Alive");
        head.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        head.put("Content-Type", "application/x-www-form-urlencoded;charset=utf8");
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        if (param != null) {
            for (String key : param.keySet()) {
                paramList.add(new BasicNameValuePair(key, param.get(key).toString()));
            }
        }

        // 发送Http请求
        RequestBase post = HttpKit.post(url);
        post.setHeaders(head);
        post.setConnectionRequestTimeout(100000);
        post.setParameters(paramList);
        String result = post.execute().getString();
        return result;
    }

3 发送json数据

/**
     * 发送JSON数据
     * 
     * @param url
     * @param param
     * @return
     */
    public static String doPostJson(String url, Map<String, Object> param) {
        // 头信息
        Map<String, String> head = new HashMap<String, String>();
        head.put("accept", "*/*");
        head.put("connection", "Keep-Alive");
        head.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        head.put("Content-Type", "application/json;charset=utf8");
        String result = HttpKit.post(url).setHeaders(head).setConnectionRequestTimeout(100000).setParameterJson(param)
                .execute().getString();
        return result;
    }
 类似资料: