`

Java模拟HTTP的Get和Post请求

阅读更多
   一、使用URLConnection实现GET和POST请求

 

    实现代码:

package test.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 
 * @author junhu
 *
 */
public class HttpUtil
{
    /**
     * 使用URLConnection实现GET请求
     * 
     * 1.实例化一个java.net.URL对象; 2.通过URL对象的openConnection()方法得到一个java.net.URLConnection;
     * 3.通过URLConnection对象的getInputStream()方法获得输入流; 4.读取输入流; 5.关闭资源;
     */
    public static void get(String urlStr) throws Exception
    {

        URL url = new URL(urlStr);
        URLConnection urlConnection = url.openConnection(); // 打开连接

        System.out.println(urlConnection.getURL().toString());

        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8")); // 获取输入流
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        br.close();
        System.out.println(sb.toString());
    }

    /**
     * 使用HttpURLConnection实现POST请求
     * 
     * 1.实例化一个java.net.URL对象; 2.通过URL对象的openConnection()方法得到一个java.net.URLConnection;
     * 3.通过URLConnection对象的getOutputStream()方法获得输出流; 4.向输出流中写数据; 5.关闭资源;
     */
    public static void post(String urlStr, Map<String, String> parameterMap) throws IOException
    {

        URL url = new URL(urlStr);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true); // 设置该连接是可以输出的
        httpURLConnection.setRequestMethod("POST"); // 设置请求方式
        httpURLConnection.setRequestProperty("charset", "utf-8");

        System.out.println(httpURLConnection.getURL().toString());

        PrintWriter pw = new PrintWriter(new BufferedOutputStream(httpURLConnection.getOutputStream()));
        
        StringBuffer parameter = new StringBuffer();
        parameter.append("1=1");
        for (Entry<String, String> entry : parameterMap.entrySet())
        {
            parameter.append("&" + entry.getKey() + "=" + entry.getValue());
        }
        pw.write(parameter.toString());// 向连接中写数据(相当于发送数据给服务器)
        
        pw.flush();
        pw.close();

        System.out.println("parameter: " + parameter.toString());

        BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null)
        { // 读取数据
            sb.append(line + "\n");
        }
        br.close();
        System.out.println(sb.toString());
    }
}

    测试代码:

package test.http;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import test.util.HttpClientUtil;

/**
 * http通信测试
 * 
 * @author junhu
 */
public class TestHttp
{
    public static void main(String[] args)
    {
        try
        {
            // --------------测试请求/test/index begin---------------------------
            // HttpUtil.get("http://localhost:8080/Java_http/test/index?name=zhangsan&age=22&sex=nan");

            // Map<String, String> parameterMap = new HashMap<String, String>();
            // parameterMap.put("name", "zhangsan");
            // parameterMap.put("age", "22");
            // parameterMap.put("sex", "nan");
            // HttpUtil.post("http://localhost:8080/Java_http/test/index", parameterMap);
            // --------------测试请求/test/index end---------------------------

            // --------------测试请求/test/index2 begin---------------------------
            // HttpUtil.get("http://localhost:8080/Java_http/test/index2?userName=zhangsan&userAge=22&userSex=nan");

            // Map<String, String> parameterMap = new HashMap<String, String>();
            // parameterMap.put("userName", "zhangsan");
            // parameterMap.put("userAge", "22");
            // parameterMap.put("userSex", "nan");
            // HttpUtil.post("http://localhost:8080/Java_http/test/index2", parameterMap);
            // --------------测试请求/test/index2 end---------------------------
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
 二、使用 HttpClient实现GET和POST请求

 

    实现代码:

package test.util;

import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 
 * @author junhu
 *
 */
public class HttpClientUtil
{
    /**
     * 使用httpclient进行http通信
     * 
     * Get请求
     */
    public static void httpclientGet(String urlStr) throws Exception
    {

        System.out.println(urlStr);

        // 创建HttpClient对象
        HttpClient client = HttpClients.createDefault();

        // 创建GET请求(在构造器中传入URL字符串即可)
        HttpGet get = new HttpGet(urlStr);

        // 调用HttpClient对象的execute方法获得响应
        HttpResponse response = client.execute(get);

        // 调用HttpResponse对象的getEntity方法得到响应实体
        HttpEntity httpEntity = response.getEntity();

        // 使用EntityUtils工具类得到响应的字符串表示
        String result = EntityUtils.toString(httpEntity, "utf-8");
        System.out.println(result);
    }

    /**
     * 使用httpclient进行http通信
     * 
     * Post请求
     */
    public static void httpclientPost(String urlStr, List<NameValuePair> parameters) throws Exception
    {

        System.out.println(urlStr);

        // 创建HttpClient对象
        HttpClient client = HttpClients.createDefault();

        // 创建POST请求
        HttpPost post = new HttpPost(urlStr);

        // 创建一个List容器,用于存放基本键值对(基本键值对即:参数名-参数值)--> parameters

        // 向POST请求中添加消息实体
        post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));

        // 得到响应并转化成字符串
        HttpResponse response = client.execute(post);
        HttpEntity httpEntity = response.getEntity();
        String result = EntityUtils.toString(httpEntity, "utf-8");
        System.out.println(result);
    }
}

    测试代码:

package test.http;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import test.util.HttpClientUtil;

/**
 * http通信测试
 * 
 * @author junhu
 */
public class TestHttp
{
    public static void main(String[] args)
    {
        try
        {
            // --------------测试请求/test/index begin---------------------------
            // HttpClientUtil
            // .httpclientGet("http://localhost:8080/Java_http/test/index?name=zhangsan&age=22&sex=nan");

            // List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            // parameters.add(new BasicNameValuePair("name", "zhangsan"));
            // parameters.add(new BasicNameValuePair("age", "22"));
            // parameters.add(new BasicNameValuePair("sex", "nan"));
            // HttpClientUtil.httpclientPost("http://localhost:8080/Java_http/test/index", parameters);
            // --------------测试请求/test/index end---------------------------

            // --------------测试请求/test/index2 begin---------------------------
            // HttpClientUtil
            // .httpclientGet("http://localhost:8080/Java_http/test/index2?userName=zhangsan&userAge=22&userSex=nan");

            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("userName", "zhangsan"));
            parameters.add(new BasicNameValuePair("userAge", "22"));
            parameters.add(new BasicNameValuePair("userSex", "nan"));
            HttpClientUtil.httpclientPost("http://localhost:8080/Java_http/test/index2", parameters);
            // --------------测试请求/test/index2 end---------------------------
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
 三、模拟POST请求发送JSON参数

 

    实现测试代码:

package test.http;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.util.EntityUtils;

public class TestHttpWithJSON
{

    public static void httpPostWithJSON(String url, String json)
    {
        // 创建默认的httpClient实例
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try
        {
            // 创建httppost
            HttpPost httppost = new HttpPost(url);
            httppost.addHeader("Content-type", "application/json; charset=utf-8");
            System.out.println("executing request " + httppost.getURI());

            // 向POST请求中添加消息实体
            StringEntity se = new StringEntity(json, "UTF-8");
            httppost.setEntity(se);
            System.out.println("request parameters " + json);

            // 执行post请求
            CloseableHttpResponse response = httpclient.execute(httppost);
            try
            {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null)
                {
                    // 打印响应内容
                    System.out.println("--------------------------------------");
                    System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                    System.out.println("--------------------------------------");
                }
            }
            finally
            {
                response.close();
            }
        }
        catch (Exception e)
        {
            System.out.println("executing httpPostWithJSON error: " + e.getMessage());
        }
        finally
        {
            // 关闭连接,释放资源
            try
            {
                httpclient.close();
            }
            catch (IOException e)
            {
                System.out.println("executing httpPostWithJSON error: " + e.getMessage());
            }
        }
    }

    public static void main(String[] args)
    {
        // JsonObject jsonObject = new JsonObject();
        // jsonObject.addProperty("userName", "张三");
        // jsonObject.addProperty("userAge", "22");
        // jsonObject.addProperty("userSex", "男");
        // String url = "http://localhost:8080/Java_http/test/index3";
        // httpPostWithJSON(url, jsonObject.toString());

        String url = "http://localhost:8080/Java_http/test/index3";
        String json = "{\"userName\":\"张三\",\"userAge\":\"22\",\"userSex\":\"男\"}";
        httpPostWithJSON(url, json);
    }
}
 四、以下是公共的处理请求的代码(控制器)
package test.controller;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import test.bean.User;

/**
 * @author junhu
 */
@Controller
@RequestMapping("/test")
public class TestController {

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String testGet(HttpServletRequest request, HttpServletResponse response)
    {
        System.out.println(request.getParameter("name"));
        System.out.println(request.getParameter("age"));
        System.out.println(request.getParameter("sex"));
        return "success";
    }

    @RequestMapping(value = "/index", method = RequestMethod.POST)
    public String testPost(HttpServletRequest request, HttpServletResponse response)
    {
        System.out.println(request.getParameter("name"));
        System.out.println(request.getParameter("age"));
        System.out.println(request.getParameter("sex"));
        return "success";
    }

    @RequestMapping(value = "/index2", method = RequestMethod.GET)
    public String testGetByObject(@ModelAttribute("user") User user, Model model)
    {
        System.out.println(user.getUserName());
        System.out.println(user.getUserAge());
        System.out.println(user.getUserSex());
		return "success";
	}

    @RequestMapping(value = "/index2", method = RequestMethod.POST)
    public String testPostByObject(@ModelAttribute("user") User user, Model model)
    {
        System.out.println(user.getUserName());
        System.out.println(user.getUserAge());
        System.out.println(user.getUserSex());
        return "success";
    }

    @RequestMapping(value = "/index3", method = RequestMethod.POST)
    public @ResponseBody User testPostByJson(@RequestBody User user, Model model)
    {
        System.out.println(user.getUserName());
        System.out.println(user.getUserAge());
        System.out.println(user.getUserSex());
        return user;
    }
}
   

   转载请注明出处:http://xieke90.iteye.com/blog/2259953

 
8
2
分享到:
评论

相关推荐

    后台模拟发送GET和POST请求

    使用HttpClient模拟GET和POST请求,主要涉及以下几个步骤: 1. 创建HttpClient实例:这是所有操作的基础,通过`HttpClientBuilder`或`HttpClients`类可以创建HttpClient对象。 ```java CloseableHttpClient ...

    java HttpClient 发送GET请求和带有表单参数的POST请求教程例子

    ### Java HttpClient 发送GET请求和带有表单参数的POST请求详解 #### 一、概述 在Java编程中,处理HTTP请求是一项常见的需求,特别是在与Web服务进行交互时。Apache HttpClient库提供了一种强大的方法来执行HTTP...

    HttpClient模拟get,post请求并发送请求参数(json等)

    它允许开发者模拟GET和POST等HTTP请求,并可以方便地发送JSON等数据作为请求参数。在本文中,我们将深入探讨如何使用HttpClient进行HTTP请求操作,以及如何处理JSON数据。 首先,我们需要引入HttpClient的相关依赖...

    Java 模拟Ajax POST GET 提交代码

    Java 模拟Ajax POST GET 提交代码,实测很好用。

    java 发送get ,post请求,高效便捷,并发性强,原生代码

    java发送get,post请求,可以实现与后台交互,代码便捷高效,是原生代码,支持并发性;代码结构清晰易懂,容易上手;

    Java发送post,get请求

    java模拟HTTP发送post和get请求工具类,使用httpClient类

    java后台实现 get post 提交.zip

    以上代码展示了如何在Java后台实现GET和POST请求的基本过程。在实际应用中,我们通常会使用框架如Spring MVC,它提供了更高级的抽象,使得处理HTTP请求变得更加便捷。Spring MVC允许我们定义控制器方法,这些方法...

    (完整版)JAVA利用HttpClient进行POST请求(HTTPS).doc

    在示例代码中,我们使用HttpGet对象来发送POST请求,并指定请求的URL、请求头和请求体。 使用HttpClient发送POST请求可以帮助我们与HTTPS服务器进行交互,但需要注意证书验证过程。使用X509TrustManager可以忽略...

    《转》Java模拟HTTP的Get和Post请求

    NULL 博文链接:https://tujunlan.iteye.com/blog/1997745

    Java模拟HTTP Get Post请求 轻松实现校园BBS自动回帖

    总的来说,Java模拟HTTP Get和Post请求涉及到网络通信、HTTP协议理解和数据处理等多个方面。在实现校园BBS自动回帖时,除了理解基本的HTTP请求原理,还需要关注特定系统的认证机制、数据格式以及异常处理。这不仅...

    JAVA-用HttpClient来模拟浏览器GET,POST.docx

    JAVA使用HttpClient模拟浏览器GET、POST请求 在本文中,我们将介绍如何使用Apache Commons HttpClient库来模拟浏览器的GET和POST请求。HttpClient库是一个开放源码的项目,是Apache Commons项目的一部分,旨在简化...

    service_java接口远程调用_get、post、带参数远程调用_

    可以使用`HttpURLConnection`或`HttpClient`模拟POST请求,但设置请求方法为GET: ```java HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); ...

    Java模拟HTTP Get Post请求实现论坛自动回帖功能

    Java模拟HTTP GET和POST请求是网络编程中常见的任务,它允许程序模拟用户在浏览器上的行为,例如在论坛上发帖或回帖。本教程将详细介绍如何使用Java来实现这一功能,特别是针对论坛自动回帖的场景。 首先,HTTP GET...

    HttpUtils Java get post 工具类

    总结,"HttpUtils Java get post 工具类"是用于简化Java中HTTP GET和POST请求的实用工具,它还支持小文件的发送。通过这个工具类,开发者可以快速地进行网络请求,而无需关注底层HTTP连接的复杂性。同时,通过测试类...

    java后端请求HTTP需要用到的jar包及其测试方法(get和post)

    测试过程中,可以使用JUnit或其他测试框架来编写单元测试,模拟不同的请求场景,确保HTTP请求能正确发送和接收。测试内容应包括但不限于:正常请求、错误处理、超时设置、连接管理、异步请求等。 总结来说,利用...

    使用Java模拟http请求.rar

    Java作为一种多用途的编程语言,提供了丰富的库来帮助开发者模拟HTTP请求,使得我们可以在程序中实现与服务器的交互,比如发送GET、POST请求,获取网页数据,甚至进行文件上传等操作。本教程将详细讲解如何使用Java...

    java http 发送 put delete post get请求

    是一个Java 发送http put、delete、 post、 get 请求的工具类。可用在与restful service 进行通讯的代码中。

    Java模拟get/post登陆(含验证码)

    本篇文章将深入探讨如何使用Java模拟GET/POST登录,特别是涉及验证码处理的情况。我们将主要关注Httpclient库的使用,以及可能涉及到的图像识别技术(OCR)。 首先,让我们了解一下HTTP的基本概念。HTTP是超文本...

Global site tag (gtag.js) - Google Analytics