Http Post Get

本文介绍了一个简单的HTTP客户端类,该类封装了GET和POST请求的方法,包括设置超时时间、发送请求及解析响应。通过实例演示如何使用此类进行HTTP交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.npnets.tools;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * 
 * @author Mr.zhang
 *
 */
public class HttpClient {
    private static Logger logger = Logger.getLogger("POST");

    /**
     * POST
     * @param url
     * @param body
     * @return
     */
    public static String sendPost(String url,String body){
        //创建http连接
        CloseableHttpClient client = HttpClientBuilder.create().build();
        //创建post请求
        HttpPost post = new HttpPost(url.trim());
        //设置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(5000)
            .setConnectTimeout(5000)
            .setSocketTimeout(5000).build();
        post.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        String res = null;
        try {
            if(StringUtils.isNotEmpty(body)){
                StringEntity entity = new StringEntity(body, "utf-8");
                post.setEntity(entity);
            }
            response = client.execute(post);
            if(response.getStatusLine().getStatusCode()==200){
                logger.info("StatusCode:[ "+response.getStatusLine().getStatusCode()+" ] post url:{"+url+"}"+"post package: "+body);
                HttpEntity entity = response.getEntity();
                res = EntityUtils.toString(entity, "utf-8");
                logger.info("crm return:  "+res);
            }else{
                logger.error("StatusCode:["+response.getStatusLine().getStatusCode()+"] post url:{ "+url+"}"+" post package: "+body);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            logger.error("post :异常"+e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("post :异常"+e.toString());
        } finally {
            //释放连接
            post.releaseConnection();
            try {
                client.close();//关闭CloseableHttpClient
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("Post 关闭CloseableHttpClient异常!!");
            }
        }
        return res;
    }


    /**
     * GET 
     * @param url
     * @return
     */
    public static String sendGet(String url){
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url.trim());
        RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(500000)
            .setConnectTimeout(500000)
            .setSocketTimeout(500000).build();
        get.setConfig(requestConfig);
        CloseableHttpResponse response = null ;
        String res = null;
        try {
            response = client.execute(get);
            System.out.println(response.getStatusLine().getStatusCode());
            if(response.getStatusLine().getStatusCode()==200){
                HttpEntity entity = response.getEntity();
                res = EntityUtils.toString(entity,"gb2312");
                System.out.println(res);
            }else{
                logger.info("get 请求失败!");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            get.releaseConnection();
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("Get 关闭CloseableHttpClient 异常!");
            }
        }
        return res;
    }


    public static void main(String[] args) {
        /*String url = "http://192.168.0.35:8080/event/sessionStat";
        String body = "{'event':201,'agentid':132,'calltype':2,'callstate':1,'username':'1003','caller':'1003','called':'013917214961','callid':1000001,'recorderid':'201508061458351000001@192.168.0.202','squenceid':'normal','begintime':'2015-08-07 15:55:16','callusertime':'','alertingtime':'2015-08-07 15:55:16','connecttime':'2015-08-07 15:55:23','releasetime':'2015-08-07 15:55:49','relreason':16,'calltransferinfo':'','satisfied':0,'recorderfilename':'20150807_013917214961_1000001.wav'}";
        String result = HttpClient.sendPost(url, body);
        //String result = client.sendGet(url);
        //System.out.println("result="+result);
*/  
        /*String msg = "{'event':302,'agentid':132,'interphone':'90010001','total':10,'dial':0,'alerting':1,'talk':0,'other':0,'alltotal':20}";
        SendMessage send = new SendMessage(msg, 3980);
        send.start();*/

        String url = "http://www.ip138.com:8080/search.asp?mobile=18696180868&action=mobile";
        String a = HttpClient.sendGet(url);
        System.out.println(a);
    }



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值