JAVA发送GET、POST请求
JAVA发送GET、POST请求
巨型河马兽 发表于3年前
JAVA发送GET、POST请求
  • 发表于 3年前
  • 阅读 1432
  • 收藏 37
  • 点赞 0
  • 评论 0

【腾讯云】新注册用户域名抢购1元起>>>   

摘要: 使用HttpClient发送GET、POST请求

注意:本文使用 httpcomponents-client-4.4 版,和以前的 3.X 版本有较大区别。

一、创建一个servlet来接收get或post请求

package guwen;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class TestServlet extends HttpServlet{

    /**
     * 接收get请求
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        System.out.println(req.getQueryString());  //打印参数
        PrintWriter out = resp.getWriter();
        out.print("响应");  //响应
    }

    /**
     * 接收post请求
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        req.setCharacterEncoding("UTF-8");
        System.out.println(req.getQueryString());  //打印参数
        InputStream inputStream = req.getInputStream();
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(inputStream);  //报文体
            System.out.println(document.asXML());
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        PrintWriter out = resp.getWriter();
        out.print("响应");  //响应
    }

    
}

二、发送请求

package guwen;

import java.io.IOException;

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;


public class ConnectionUtil {
    
    public static void main(String[] args) throws ClientProtocolException, IOException {
        //sent get
        sendGet("http://localhost:8088/sentTest/test?p=123");
        //sent post
        sendPost("http://localhost:8088/sentTest/test?p=321","<xml><a>aa</a><b>哈</b></xml>");
    }
    
    /**
     * 发送get请求
     * @throws IOException 
     */
    public static String sendGet(String url) throws ClientProtocolException, IOException {
        
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();  
        
        HttpGet httpGet = new HttpGet(url);     
  
        //配置请求的超时设置  
        RequestConfig requestConfig = RequestConfig.custom()    
                .setConnectionRequestTimeout(50)  
                .setConnectTimeout(50)    
                .setSocketTimeout(50).build();    
        httpGet.setConfig(requestConfig);   
          
        CloseableHttpResponse response = null;
        String res = null;
        try {
            response = httpClient.execute(httpGet);   //发送请求
            System.out.println("StatusCode -> " + response.getStatusLine().getStatusCode());  
            HttpEntity entity = response.getEntity();          
            res = EntityUtils.toString(entity,"utf-8");   
            System.out.println(res);  
        } catch (ClientProtocolException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } finally{
            httpGet.releaseConnection(); 
        }
          
        return res;
    }
    
    
    
    /**
     * 发送post请求
     * @throws IOException 
     */
    public static String sendPost(String url,String body) throws IOException {
        
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();  
        HttpPost httpPost = new HttpPost(url);
        //配置请求的超时设置  
        RequestConfig requestConfig = RequestConfig.custom()    
                .setConnectionRequestTimeout(50)  
                .setConnectTimeout(50)    
                .setSocketTimeout(50).build();    
        httpPost.setConfig(requestConfig); 
        
        CloseableHttpResponse response = null;
        String res = null;
        try {
            if (body != null) {  //设置报文体 设置编码为 UTF-8
                StringEntity entity = new StringEntity(body, "UTF-8");
                httpPost.setEntity(entity);
            }
            response = httpclient.execute(httpPost);  //发送请求
            System.out.println(response.toString());  
            
            HttpEntity entity = response.getEntity();  
            res = EntityUtils.toString(entity, "utf-8");  
            System.out.println(res);  
        } catch (ClientProtocolException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } finally{
            httpPost.releaseConnection();
        }
        
        return res;
        
        
    }
    
    
}


  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 1
博文 5
码字总数 2512
×
巨型河马兽
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: