JAVA HTTP POST转发请求

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Service
public class HttpService {

    // 创建HttpClient对象
    @Autowired(required = false)
    private CloseableHttpClient httpClient;

    /* @Autowired(required = false)表示的含义是,spring容器里面有这个bean就注入,没有就不注入。 */

    // 请求信息的配置
    @Autowired(required = false)
    private RequestConfig requestConfig;

    /**
     * 执行Get请求
     * 
     * @param url
     * @return 请求到的内容
     * @throws URISyntaxException
     * @throws IOException
     * @throws ClientProtocolException
     */
    public String doGet(String url) throws URISyntaxException, ClientProtocolException, IOException {

        return doGet(url, null);

    }

    /**
     * @param url
     * @param intoParams 请求中的参数
     * @return 请求到的内容
     * @throws URISyntaxException
     * @throws ClientProtocolException
     * @throws IOException
     */
    public String doPost(String url) throws URISyntaxException, ClientProtocolException, IOException {

        return doPost(url, null);

    }

    /**
     * 执行Get请求
     * 
     * @param url
     * @param params 请求中的参数
     * @return 请求到的内容
     * @throws URISyntaxException
     * @throws IOException
     * @throws ClientProtocolException
     */
    public String doGet(String url, Map<String, Object> params) throws URISyntaxException, ClientProtocolException, IOException {
        // 定义请求的参数
        URI uri = null;
        if (params != null) {
            URIBuilder builder = new URIBuilder(url);
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                builder.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
            }
            uri = builder.build();
        }

        // 创建http GET请求
        HttpGet httpGet = null;
        if (uri != null) {
            httpGet = new HttpGet(uri);
        } else {
            httpGet = new HttpGet(url);
        }
        // 设置请求参数
        httpGet.setConfig(this.requestConfig);

        // 请求的结果
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 获取服务端返回的数据,并返回
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }

    /**
     * @param url
     * @param params 请求中的参数
     * @return 请求到的内容
     * @throws URISyntaxException
     * @throws ClientProtocolException
     * @throws IOException
     */
    public String doPost(String url, Map<String, Object> params)
            throws URISyntaxException, ClientProtocolException, IOException {
        // url = GlobalUtil.getValue("remoteAddress") + url;
        // 设置post参数
        List<NameValuePair> parameters = null;
        // 构造一个form表单式的实体
        UrlEncodedFormEntity formEntity = null;
        // 定义请求的参数
        if (params != null) {
            // 设置post参数
            parameters = new ArrayList<NameValuePair>();

            for (Map.Entry<String, Object> entry : params.entrySet()) {
                // 添加参数
                parameters.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));

            }
            // 构造一个form表单式的实体
            formEntity = new UrlEncodedFormEntity(parameters);
        }

        // 创建HTTP GET请求
        HttpPost httpPost = null;

        if (formEntity != null) {

            httpPost = new HttpPost(url);
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(formEntity);
            // 伪装浏览器请求
            httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
        } else {
            httpPost = new HttpPost(url);
            // 伪装浏览器请求
            httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
        }
        // 设置请求参数
        httpPost.setConfig(this.requestConfig);
        // 请求的结果
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 获取服务端返回的数据,并返回
                return EntityUtils.toString(response.getEntity(), "UTF-8");

            }
        } finally {

            if (response != null) {

                response.close();

            }

        }

        return null;

    }

    /**使用post以“raw-JSON(application/json)”类型推送数据
     * @param url
     * @param params 请求中的参数
     * @return 请求到的内容
     * @throws URISyntaxException
     * @throws ClientProtocolException
     * @throws IOException
     */
    public String httpPostWithJSON(String url, Map<String, Object> params) throws URISyntaxException, ClientProtocolException, IOException {

        CloseableHttpClient client = HttpClients.createDefault();
        // 设置post参数
        StringEntity entity = null;
        // 构造一个form表单式的实体
        // 定义请求的参数
        if (params != null) {
            // 设置post参数
            String json = JSON.toJSONString(params);// map转String
            JSONObject jsonObject = JSON.parseObject(json);// String转json
            entity = new StringEntity(jsonObject.toString(), "utf-8");// 解决中文乱码问题
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
        }

        // 创建HTTP GET请求
        HttpPost httpPost = new HttpPost(url);

        httpPost.setEntity(entity);

        try {
            // 执行请求
            HttpResponse response = client.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 获取服务端返回的数据,并返回
                return EntityUtils.toString(response.getEntity(), "UTF-8");

            }
        } finally {

            if (client != null) {

                client.close();

            }

        }

        return null;

    }

    /**
     * 使用post以“x-www-form-urlencoded”类型推送数据
     * 
     * @param url
     * @param params 请求中的参数
     * @return 请求到的内容
     */
    public String httpSendPost(String url, Map<String, Object> params) {
        StringBuffer resultBuffer = null;
        // 构建请求参数
        StringBuffer sbParams = new StringBuffer();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> e : params.entrySet()) {
                sbParams.append(e.getKey());
                sbParams.append("=");
                sbParams.append(e.getValue());
                sbParams.append("&");
            }
        }
        URLConnection con = null;
        OutputStreamWriter osw = null;
        BufferedReader br = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            con = realUrl.openConnection();
            // 设置通用的请求属性
            con.setRequestProperty("accept", "*/*");
            con.setRequestProperty("connection", "Keep-Alive");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            con.setDoOutput(true);
            con.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            osw = new OutputStreamWriter(con.getOutputStream(), "utf-8");
            if (sbParams != null && sbParams.length() > 0) {
                // 发送请求参数
                osw.write(sbParams.substring(0, sbParams.length() - 1));
                // flush输出流的缓冲
                osw.flush();
            }
            // 定义BufferedReader输入流来读取URL的响应
            resultBuffer = new StringBuffer();
            int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
            if (contentLength > 0) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
                String temp;
                while ((temp = br.readLine()) != null) {
                    resultBuffer.append(temp);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (osw != null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    osw = null;
                    throw new RuntimeException(e);
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    br = null;
                    throw new RuntimeException(e);
                }
            }
        }
        return resultBuffer.toString();
    }

}
 

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java中,你可以使用Servlet来处理HTTP请求。如果你想将一个POST请求处理完后转发成GET请求,可以按照以下步骤进行操作: 1. 在处理POST请求的Servlet中,获取POST请求的参数,并处理请求。 2. 在处理完POST请求后,使用request对象的setAttribute()方法将需要传递给GET请求的参数设置到request对象中。 3. 使用response对象的sendRedirect()方法将请求重定向到GET请求的Servlet。 4. 在处理GET请求的Servlet中,使用request对象的getAttribute()方法获取从POST请求中传递过来的参数,并处理请求。 以下是一个示例代码: 在处理POST请求的Servlet中: ``` protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取POST请求的参数,并处理请求 String param1 = request.getParameter("param1"); String param2 = request.getParameter("param2"); // 处理请求... // 将需要传递给GET请求的参数设置到request对象中 request.setAttribute("param3", "value3"); request.setAttribute("param4", "value4"); // 将请求重定向到GET请求的Servlet response.sendRedirect("getServlet"); } ``` 在处理GET请求的Servlet中: ``` protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 使用request对象的getAttribute()方法获取从POST请求中传递过来的参数 String param3 = (String) request.getAttribute("param3"); String param4 = (String) request.getAttribute("param4"); // 处理请求... } ``` 在上面的示例中,我们首先在处理POST请求的Servlet中获取POST请求的参数,并处理请求。然后,我们将需要传递给GET请求的参数设置到request对象中,并使用sendRedirect()方法将请求重定向到GET请求的Servlet。在处理GET请求的Servlet中,我们使用getAttribute()方法获取从POST请求中传递过来的参数,并处理请求

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NuoleAQ

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值