httpclient get post

Posted yaowen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了httpclient get post相关的知识,希望对你有一定的参考价值。

https://www.cnblogs.com/wutongin/p/7778996.html

 

post请求方法和get请求方法

 

package com.xkeshi.paymentweb.controllers.test;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
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 java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jiangzw on 2017/11/3.
 */
public class MyTestHttpClient {

    /**
     * post方式提交表单(模拟用户登录请求)
     */
    public static void doFormPost() {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        String url = "http://localhost:8888/myTest/testHttpClientPost";
        HttpPost httppost = new HttpPost(url);
        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("username", "admin"));
        formparams.add(new BasicNameValuePair("password", "123456"));
        UrlEncodedFormEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(entity);
            System.out.println("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content: " + EntityUtils.toString(resEntity, "UTF-8"));
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送 get请求
     */
    public static void doGet() {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建参数队列
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", "admin"));
        params.add(new BasicNameValuePair("password", "123456"));

        try {
            //参数转换为字符串
            String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(params, "UTF-8"));
            String url = "http://localhost:8888/myTest/testHttpClientGet" + "?" + paramsStr;
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            System.out.println("executing request " + httpget.getURI());
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印响应内容长度
                    System.out.println("Response content length: " + entity.getContentLength());
                    // 打印响应内容
                    System.out.println("Response content: " + EntityUtils.toString(entity));
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * post方式提交表单(模拟用户登录请求)
     */
    public static void doStringPost() {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        String url = "http://localhost:8888/myTest/testHttpClientStringPost";
        HttpPost httppost = new HttpPost(url);
        // 创建参数字符串
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "admin");
        jsonObject.put("password", "123456");
        try {
            //设置实体内容的格式。APPLICATION_JSON = "application/json",
            // 如果传送"application/xml"格式,选择ContentType.APPLICATION_XML
            StringEntity entity = new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON);
            httppost.setEntity(entity); //发送字符串参数
            System.out.println("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content: " + EntityUtils.toString(resEntity, "UTF-8"));
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 上传文件
     */
    public static void doUploadPost() {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String url = "http://localhost:8888/myTest/testHttpClientUploadPost";
        try {
            HttpPost httppost = new HttpPost(url);

            FileBody fileBody = new FileBody(new File("D:\\img8.jpg"));
            StringBody stringBody = new StringBody("一张测试图片", ContentType.TEXT_PLAIN.withCharset("UTF-8"));

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.addPart("file", fileBody);//文件参数
            builder.addPart("explain", stringBody);//字符串参数
            HttpEntity entity = builder.build();

            httppost.setEntity(entity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content: " + EntityUtils.toString(resEntity, "UTF-8"));
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
//        doFormPost();
//        doGet();
//        doStringPost();
        doUploadPost();
    }

}



处理请求的方法

package com.xkeshi.paymentweb.controllers.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;

/**
 * Created by jiangzw on 2017/11/3.
 */
@Controller
@RequestMapping(value = "/myTest")
public class MyTestController {

    @ResponseBody
    @RequestMapping(value = "/testHttpClientPost", method = RequestMethod.POST)
    public String testHttpClientPost(@RequestParam("username") String username,
                                     @RequestParam("password") String password) {
        String result = null;

        if ("admin".equals(username) && "123456".equals(password)) {
            result = "用户名和密码验证成功!";
        } else {
            result = "用户名和密码验证失败!";
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/testHttpClientGet", method = RequestMethod.GET)
    public String testHttpClientGet(@RequestParam("username") String username,
                                    @RequestParam("password") String password) {
        String result = null;

        if ("admin".equals(username) && "123456".equals(password)) {
            result = "用户名和密码验证成功!";
        } else {
            result = "用户名和密码验证失败!";
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/testHttpClientStringPost", method = RequestMethod.POST)
    public String testHttpClientStringPost(@RequestBody String requestBody) {
        JSONObject jsonObject = JSON.parseObject(requestBody);
        String username = jsonObject.get("username").toString();
        String password = jsonObject.get("password").toString();
        String result = null;

        if ("admin".equals(username) && "123456".equals(password)) {
            result = "用户名和密码验证成功!";
        } else {
            result = "用户名和密码验证失败!";
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/testHttpClientUploadPost", method = RequestMethod.POST)
    public String testHttpClientUploadPost(@RequestParam("file") CommonsMultipartFile file,
                                           @RequestParam("explain") String explain) {

        System.out.println("explain: " + explain);
        String result = "上传失败";

        //文件保存路径和名称
        String savePath = "D:\\home" + File.separator + System.currentTimeMillis() + file.getOriginalFilename();
        File newFile= null;
        try {
            newFile = new File(savePath);
            //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
            file.transferTo(newFile);
            result = "上传成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

技术分享图片

 

以上是关于httpclient get post的主要内容,如果未能解决你的问题,请参考以下文章

WP8,怎么使用HttpClient?

HttpClient替换HttpWebRequest--以GET和POST请求为例说明

httpclient 中post请求重定向

HttpClient--使用HttpClient进行Get Post请求访问

HttpClient发送get,post接口请求

HttpClient的GET请求(post)请求