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的更多相关文章

  1. HttpClient的替代者 - RestTemplate

    需要的包 ,除了Spring的基础包外还用到json的包,这里的数据传输使用json格式 客户端和服务端都用到一下的包 <!-- Spring --> <dependency> ...

  2. 关于微软HttpClient使用,避免踩坑

    最近公司对于WebApi的场景使用也越来越加大了,随之而来就是Api的客户端工具我们使用哪个?我们最常用的估计就是HttpClient,在微软类库中命名空间地址:System.Net.Http,是一个 ...

  3. 使用HttpClient的优解

    新工作入职不满半周,目前仍然还在交接工作,适应环境当中,笔者不得不说看别人的源码实在是令人痛苦.所幸今天终于将大部分工作流畅地看了一遍,接下来就是熟悉框架技术的阶段了. 也正是在看源码的过程当中,有一 ...

  4. Java的异步HttpClient

    上篇提到了高性能处理的关键是异步,而我们当中许多人依旧在使用同步模式的HttpClient访问第三方Web资源,我认为原因之一是:异步的HttpClient诞生较晚,许多人不知道:另外也可能是大多数W ...

  5. 揭秘Windows10 UWP中的httpclient接口[2]

    阅读目录: 概述 如何选择 System.Net.Http Windows.Web.Http HTTP的常用功能 修改http头部 设置超时 使用身份验证凭据 使用客户端证书 cookie处理 概述 ...

  6. C#中HttpClient使用注意:预热与长连接

    最近在测试一个第三方API,准备集成在我们的网站应用中.API的调用使用的是.NET中的HttpClient,由于这个API会在关键业务中用到,对调用API的整体响应速度有严格要求,所以对HttpCl ...

  7. HttpClient调用webApi时注意的小问题

    HttpClient client = new HttpClient(); client.BaseAddress = new Uri(thisUrl); client.GetAsync("a ...

  8. HttpClient相关

    HTTPClient的主页是http://jakarta.apache.org/commons/httpclient/,你可以在这里得到关于HttpClient更加详细的信息 HttpClient入门 ...

  9. Atitit.http httpclient实践java c# .net php attilax总结

    Atitit.http httpclient实践java c# .net php attilax总结 1. Navtree>> net .http1 2. Httpclient理论1 2. ...

  10. 使用httpclient发送get或post请求

    HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建 ...

随机推荐

  1. Sql server 2016 Always On 搭建Windows集群配置

    .安装WSFC群集组件 1)打开服务器管理器,选择“功能”,在右边窗口中点击“添加功能”. 2)在添加功能向导中,勾选“故障转移群集”,点击“下一步”. 3)在“确认安装选择”页面中,点击“安装”,进 ...

  2. 火币网API文档——WebSocket API简介

    WebSocket API简介 WebSocket协议是基于TCP的一种新的网络协议.它实现了客户端与服务器之间在单个 tcp 连接上的全双工通信,由服务器主动发送信息给客户端,减少了频繁的身份验证等 ...

  3. docker私有仓库搭建和资源限制

    Docker 私有仓库的搭建 docker 私有仓库默认只支持https协议的访问  不支持http协议 如果需要允许通过http协议访问 必须手动修改配置文件 docker官方默认提供的仓库  提供 ...

  4. Linux系统启动和内核管理

    Linux组成 由 kernel 和 rootfs 组成 单内核:(进程管理,内存管理,网络管理, 驱动程序,文件系统, 安全功能) /boot/vmlinuz-VERSION-release 辅助的 ...

  5. 爬虫mm131明星照片

    ''' 1. 爬取以下站点中各个明星图片,分别单独建文件夹存放. 起始URL地址:http://www.mm131.com/mingxing ''' import os import logging ...

  6. 【Java】-NO.16.EBook.4.Java.1.011-【疯狂Java讲义第3版 李刚】- AWT

    1.0.0 Summary Tittle:[Java]-NO.16.EBook.4.Java.1.011-[疯狂Java讲义第3版 李刚]-  AWT Style:EBook Series:Java ...

  7. div+CSS实现页面的布局要点记录

    1.页面任何控件可以通过div包装为一个模块,然后通过margin(外补丁)和padding(内补丁)对控件位置的摆放进行控制,以实现想要的效果. 2.position:absolute;对控件实现绝 ...

  8. vue作用域 this

    设计到异步 function 回调的.this指向 需要用内部代替this 如果是箭头符号写法 就不需要 this永远是当前vue实例

  9. nginx 日志log_format格式

    官方文档: http://nginx.org/en/docs/http/ngx_http_log_module.html The ngx_http_log_module module writes r ...

  10. (转载)Windows WMIC命令使用详解(附实例)

    原文地址:http://www.jb51.net/article/49987.htm 第一次执行WMIC命令时,Windows首先要安装WMIC,然后显示出WMIC的命令行提示符.在WMIC命令行提示 ...