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();// 创建httppostString 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();// 创建httppostString 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_XMLStringEntity 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相关推荐

  1. java爬取验证码图片_JAVA HttpClient实现页面信息抓取(获取图片验证码并传入cookie实现信息获取)...

    JAVA HttpClient实现页面信息抓取(获取图片验证码并传入cookie实现信息获取) 发布时间:2018-05-18 16:41, 浏览次数:632 , 标签: JAVA HttpClien ...

  2. httpclient工具类,post请求发送json字符串参数,中文乱码处理

    在使用httpclient发送post请求的时候,接收端中文乱码问题解决. 正文: 我们都知道,一般情况下使用post请求是不会出现中文乱码的.可是在使用httpclient发送post请求报文含中文 ...

  3. 关于HttpClient上传中文乱码的解决办法

    使用过HttpClient的人都知道可以通过addTextBody方法来添加要上传的文本信息,但是,如果要上传中文的话,或还有中文名称的文件会出现乱码的问题,解决办法其实很简单: 第一步:设置Mult ...

  4. java url json字符串_使用HttpClient将URL中的JSON查询字符串发送到Web服务(Java)

    我有一个我建立的Web服务...我现在要做的是发送一个简单的请求,其中包含一个从Tapestry Web应用程序到该Web服务的json查询字符串.我四处搜索,大多数人都说使用Apache HttpC ...

  5. java rest httpclient_java http请求建议使用webClient,少用RestTemplate,不用HttpClient

    简介: webClient:是Spring-webFlux包下的,非阻塞响应,最低java8支持函数式编程,性能好 RestTemplate:是Spring-webmvc包下的,满足RestFul原则 ...

  6. 【请求后台接口】30秒完成Angular10精简版HttpClient请求服务搭建

    ng g s services/http app.module.ts ... @NgModule({declarations: [...],imports: [...HttpClientModule, ...

  7. Angular 4+ HttpClient

    个人博客迁移至 http://www.sulishibaobei.com  处: 这篇,算是上一篇Angular 4+ Http的后续: Angular 4.3.0-rc.0 版本已经发布?.在这个版 ...

  8. HttpClient学习

    HttpClient学习 (1)下面列举几个主要的Http相关概念的类 类名 描述 HttpClient 建立请求客户端 HttpGet 代表请求方法,类似的还有HttpHead, HttpPost, ...

  9. 漫谈Httpclient

    引用地址: http://hc.apache.org/httpclient-3.x/ End of life The Commons HttpClient project is now end of ...

  10. 使用HttpClient实现跨服务图片下载

    需求: 由于web系统存放图片的文件夹路径和erp系统存放图片的文件夹路径不一样 所以 web系统文件上传的文件要拷贝到erp对应的文件夹 思路: 在erp中访问图片接口的时候,如果图片不存在,则调w ...

最新文章

  1. 在安装和使用Oracle过程中可能遇到的困难及其相应的解决措施
  2. android动态切换logo和label
  3. 鸿蒙系统发布IT直播,华为开源平台上线:鸿蒙系统、方舟编译器在列
  4. Hbase完全分布式高可用集群安装配置
  5. python验证身份证最后一位数字代表什么_身份证尾数带X的人,是有什么特殊身份吗?看完涨知识了...
  6. Textarea自动换行如何设置
  7. HTML页面跳转的几种方式(重定向)
  8. SPSS之多因素方差分析
  9. c语言系统垃圾清理软件,清理系统垃圾
  10. ms17010利用失败_利用产品管理中的失败
  11. VMware安装虚拟机出现STOP: 0x0000005d错误
  12. Windows桌面共享中一些常见的抓屏技术
  13. 带你玩转以太坊智能合约的”Hello World“
  14. Linux(Ubuntu)系统查看显卡型号
  15. 【Linux系统编程】进程退出和回收进程资源
  16. 每日一书丨手把手教你构建一个通用的智能风控平台
  17. 让macOS词典具备保存单词的生词本功能
  18. 【RNN入门到实战】LSTM从入门到实战——实现空气质量预测
  19. html 手机上按比例缩放,动态rem方案等比例缩放手机页面
  20. 开源erp软件odoo在线开发环境部署实录

热门文章

  1. 头秃,在线求名字:网易使用昵称交流,再也没有“哥,姐,总”
  2. 程序员花名大 PK | 每日趣闻
  3. 将mcomaster配置以apache运行
  4. STS中applicationContext.xml配置文件
  5. 活动目录系列之三---域控制器常规卸域
  6. Spring 基于Java配置
  7. java中native的用法[转]
  8. C# 视频监控系列 序 [完]
  9. Java 8 Lambda 表达式详解
  10. Java SE 9(JDK9)环境安装及交互式编程环境Jshell使用示例