博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java http get和post请求
阅读量:5118 次
发布时间:2019-06-13

本文共 3440 字,大约阅读时间需要 11 分钟。

1.http工具类

package com.funshion.common.utils;

import java.net.URI;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * http工具类
 *
 * @author qiuwy
 *
 */
@SuppressWarnings({ "deprecation", "resource" })
public class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    /**
     * get
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static HttpResVo doGet(String getUrl) throws Exception {
        URL url = new URL(getUrl);
        URI uri = new URI(url.getProtocol(), null, url.getHost(), url.getPort(), url.getPath(), url.getQuery(), null);
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(uri);
        HttpResponse response = httpclient.execute(httpGet);
        int httpCode = response.getStatusLine().getStatusCode();
        String result = EntityUtils.toString(response.getEntity());
        logger.info("Get.url=" + uri + ",response code=" + httpCode + ",response entity=" + result);
        return new HttpResVo(httpCode, result);
    }
    /**
     * post
     *
     * @param url
     * @param params
     * @return 返回http code
     *
     */
    public static HttpResVo doPost(String url, String params) throws Exception {
        URL postUrl = new URL(url);
        URI uri = new URI(postUrl.getProtocol(), null, postUrl.getHost(), postUrl.getPort(), postUrl.getPath(), postUrl.getQuery(), null);
        
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(uri);
        
        StringEntity entity = new StringEntity(params, HTTP.UTF_8);
        entity.setContentType("application/json;charset=UTF-8");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(entity);
        HttpResponse response = httpclient.execute(httpPost);
        int httpCode = response.getStatusLine().getStatusCode();
        String result = EntityUtils.toString(response.getEntity());
        
        logger.info("Post.url=" + uri + ",response code=" + httpCode + ",response entity=" + result);
        
        return new HttpResVo(httpCode, result);
    }

    /**

     * 根据参数和url访问远程,得到返回值
     *
     * @return
     */
    protected HttpResVo getHttpResult(String url,String method,String parameter) throws Exception {
        if (StringUtils.isEmpty(method)) {
            logger.error("method is null.");
            return null;
        }
        // get方法的处理
        if (method.equalsIgnoreCase(GET)) {
            StringBuffer _url = new StringBuffer(url);
            if (!StringUtils.isEmpty(parameter)) {
                _url.append("?").append(parameter);
                System.out.println(_url.toString());
            }
            return HttpUtil.doGet(_url.toString());
        } else {// post方法处理
            if (!StringUtils.isEmpty(parameter)) {
                return HttpUtil.doPost(url, parameter);
            }
            logger.error("post method has parameter none.");
        }
        return null;
    }
}

2.http响应返回值

package com.funshion.common.utils;

/**
 * http响应返回值
 *
 * @author qiuwy
 *
 */
public class HttpResVo implements java.io.Serializable {

    private int httpCode;

    private String result;
    public HttpResVo() {
    }
    public HttpResVo(int httpCode, String result) {
        this.httpCode = httpCode;
        this.result = result;
    }
    public int getHttpCode() {
        return httpCode;
    }
    public void setHttpCode(int httpCode) {
        this.httpCode = httpCode;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }
}

 

转载于:https://www.cnblogs.com/weiweiyao/p/4385283.html

你可能感兴趣的文章
yii 跳转页面
查看>>
洛谷 1449——后缀表达式(线性数据结构)
查看>>
Data truncation: Out of range value for column 'Quality' at row 1
查看>>
Dirichlet分布深入理解
查看>>
字符串处理
查看>>
HtmlUnitDriver 网页内容动态抓取
查看>>
ad logon hour
查看>>
获得进程可执行文件的路径: GetModuleFileNameEx, GetProcessImageFileName, QueryFullProcessImageName...
查看>>
证件照(1寸2寸)拍摄处理知识汇总
查看>>
罗马数字与阿拉伯数字转换
查看>>
Eclipse 反编译之 JadClipse
查看>>
Python入门-函数
查看>>
[HDU5727]Necklace(二分图最大匹配,枚举)
查看>>
距离公式汇总以及Python实现
查看>>
一道不知道哪里来的容斥题
查看>>
Blender Python UV 学习
查看>>
window添加右键菜单
查看>>
入手腾龙SP AF90mm MACRO
查看>>
Window7上搭建symfony开发环境(PEAR)
查看>>
Linux内核态、用户态简介与IntelCPU特权级别--Ring0-3
查看>>