首页 > 编程语言 > 详细

JAVA发送GET、POST请求

时间:2015-02-10 23:17:18      阅读:559      评论:0      收藏:0      [点我收藏+]

注意:本文使用 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
        doGet("http://localhost:8088/sentTest/test?p=123");
        //sent post
        doPost("http://localhost:8088/sentTest/test?p=321","<xml><a>aa</a><b>哈</b></xml>");
    }
    
    /**
     * 发送get请求
     * @throws IOException 
     */
    public static String doGet(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;
    }
    
    
    
    /**
     * 发送get请求
     * @throws IOException 
     */
    public static String doPost(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;
        
        
    }
    
    
}


JAVA发送GET、POST请求

原文:http://my.oschina.net/u/2309120/blog/377474

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!