1、Pom文件添加httpClient 依赖

        <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.</version>
</dependency>

2、 HttpGet

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; public class HttpTest {
// main Alt+?
public static void main(String[] args) {
// 1.创建一个httpclient,默认的
CloseableHttpClient client = HttpClients.createDefault();
// 2.创建一个get请求方法
HttpGet get = new HttpGet("http://mail.163.com");
CloseableHttpResponse response = null;
try { /////
// 3.执行请求,获取到响应
response = client.execute(get); System.out.println(response.getStatusLine());// 状态行
System.out.println(response.getStatusLine().getStatusCode());// 状态码
System.out.println(response.getStatusLine().getProtocolVersion());// 协议版本
System.out.println(response.getStatusLine().getReasonPhrase());// 响应描述 System.out.println("######################");
Header[] allHeaders = response.getAllHeaders();
System.out.println(allHeaders.length);
for (int i = ; i < allHeaders.length; i++) {
System.out.println(allHeaders[i]);
}
System.out.println("################");
System.out.println(response.getFirstHeader("Server"));
System.out.println(response.getFirstHeader("Server").getValue());// 获取value
System.out.println(response.getFirstHeader("Content-Type").getValue());// 获取value System.out.println("################");
// 实体
HttpEntity entity = response.getEntity();
// 获取实体类型
System.out.println(entity.getContentType());
// 实体长度,文件下载最常用,一般网页无此参数
System.out.println(entity.getContentLength());
// EntityUtils实体类的工具包 ,将实体对象转成Stirng或者byte
System.out.println(EntityUtils.toString(entity, "utf-8"));// 可以指定编码格式(中文:utf-8或者GBK) } catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (response != null)
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// syso Alt+?
System.out.println();
}
}

3、HttpPost请求

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List; import org.apache.http.HeaderIterator;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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; public class LoginTest {
public static void main(String[] args) {
CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost("http://localhost/loginController/loginPage");
// 表单参数,并放入list中
NameValuePair username = new BasicNameValuePair("userName", "taki");
NameValuePair password = new BasicNameValuePair("password", ""); List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(username);
paramList.add(password); CloseableHttpResponse response = null;
try {
// form实体,放入到请求中
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
post.setEntity(entity); response = client.execute(post);
System.out.println(response.getStatusLine().getStatusCode());
// 根据返回码,200为成功,继续操作
if (response.getStatusLine().getStatusCode() == ) {
// 读取header
HeaderIterator headerIterator = response.headerIterator();
while (headerIterator.hasNext()) {
System.out.println(headerIterator.next());
}
System.out.println("####################");
// 读取实体
System.out.println(EntityUtils.toString(response.getEntity())); } } catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

4、HttpPost 请求Json数据(该接口不通)

import java.io.IOException;
import java.io.UnsupportedEncodingException; import org.apache.http.HeaderIterator;
import org.apache.http.client.ClientProtocolException;
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 JsonTest { public static void main(String[] args) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://117.122.238.33/webservice/services/Rest/account");
post.setHeader("Content-Type", "application/json");
CloseableHttpResponse response = null;
try {
StringEntity entity = new StringEntity(
"{\"name\": \"jiaminqiang\",\"billingAddress\": \"beijing\", \"phoneNumber\": \"15801396646\"}");
post.setEntity(entity); response = client.execute(post);
System.out.println(response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode() == ) {
HeaderIterator headerIterator = response.headerIterator();
while(headerIterator.hasNext()) {
System.out.println(headerIterator.next());
}
System.out.println("##############");
System.out.println(EntityUtils.toString(response.getEntity()));
} } catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(response!=null) {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} } }

5、Http添加Header

import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.message.BasicHttpResponse; public class HeaderTest { public static void main(String[] args) {
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, , "not found");
// request 操作header同response
HttpRequest request = new BasicHttpRequest("post", "mail.163.com");
request.addHeader("", "");
//添加header name唯一
response.setHeader("Set-Cookie", "test1");
response.setHeader("Set-Cookie2", "test");
//添加header name可重复
response.addHeader("Set-Cookie", "test2");
// Ctrl + 2 l 自动生成返回类型变量
Header[] allHeaders = response.getAllHeaders();
// Ctrl + d 删除一行
// Ctrl + Shift + f 代码格式化
// Ctrl + / 注释一行
// Ctrl + Shift + / 多行注释
// Ctrl + z 撤销
// Ctrl + s 保存
// Header[] allHeaders3 = response.getAllHeaders();
// String [] s = {"1","2","aa"};
// for(int i = 0;i<s.length;i++) {
// System.out.println(s[i]);
// } for (int i = ; i < allHeaders.length; i++) {
System.out.println(allHeaders[i]);
} System.out.println(response.getStatusLine()); System.out.println(response.getFirstHeader("Set-Cookie"));
System.out.println(response.getLastHeader("Set-Cookie"));
Header[] headers = response.getHeaders("Set-Cookie");
System.out.println(headers[]);
System.out.println(headers[]);
// 遍历迭代器
HeaderIterator headerIterator = response.headerIterator();
// System.out.println(headerIterator.nextHeader());
// System.out.println(headerIterator.nextHeader());
System.out.println("###################"); while (headerIterator.hasNext()) {
System.out.println(headerIterator.nextHeader());
}
} }

HttpClient-get请求/Post请求/Post-Json/Header的更多相关文章

  1. HttpClient (POST GET PUT)请求

    HttpClient (POST GET PUT)请求 package com.curender.web.server.http; import java.io.IOException; import ...

  2. httpclient实现的get请求及post请求

    导出mven依赖 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId& ...

  3. HttpClient方式模拟http请求设置头

    关于HttpClient方式模拟http请求,请求头以及其他参数的设置. 本文就暂时不给栗子了,当作简版参考手册吧. 发送请求是设置请求头:header HttpClient httpClient = ...

  4. HttpClient的get+post请求使用

    啥都不说,先上代码 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReade ...

  5. HttpClient发送get post请求和数据解析

    最近在跟app对接的时候有个业务是微信登录,在这里记录的不是如何一步步操作第三方的,因为是跟app对接,所以一部分代码不是由我写,我只负责处理数据,但是整个微信第三方的流程大致都差不多,app端说要传 ...

  6. HttpWebRequest 改为 HttpClient 踩坑记-请求头设置

    HttpWebRequest 改为 HttpClient 踩坑记-请求头设置 Intro 这两天改了一个项目,原来的项目是.net framework 项目,里面处理 HTTP 请求使用的是 WebR ...

  7. spring boot get和post请求,以及requestbody为json串时候的处理

    GET.POST方式提时, 根据request header Content-Type的值来判断: application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的 ...

  8. httpclient的几种请求URL的方式

    一.httpclient项目有两种使用方式.一种是commons项目,这一个就只更新到3.1版本了.现在挪到了HttpComponents子项目下了,这里重点讲解HttpComponents下面的ht ...

  9. [SoapUI] 通过SoapUI发送POST请求,请求的body是JSON格式的数据

    通过SoapUI发送POST请求,请求的body是JSON格式的数据: data={"currentDate":"2015-06-19","reset ...

  10. 我的Android进阶之旅------>android如何将List请求参数列表转换为json格式

    本文同步发表在简书,链接:http://www.jianshu.com/p/395a4c8b05b9 前言 由于接收原来的老项目并进行维护,之前的http请求是使用Apache Jakarta Com ...

随机推荐

  1. CodeForces 1294B Collecting Packages(排序+贪心)

    http://codeforces.com/contest/1294/problem/B 大致题意: 一张图上有n个包裹,给出他们的坐标,一个机器人从(0,0)出发,只能向右(R)或向上(U),问能否 ...

  2. Istio流量治理原理之负载均衡

    流量治理是一个非常宽泛的话题,例如: ● 动态修改服务间访问的负载均衡策略,比如根据某个请求特征做会话保持: ● 同一个服务有两个版本在线,将一部分流量切到某个版本上: ● 对服务进行保护,例如限制并 ...

  3. 吴裕雄--天生自然 JAVA开发学习:String 类

    public class StringDemo{ public static void main(String args[]){ char[] helloArray = { 'r', 'u', 'n' ...

  4. 数组,字符串方法总结 Unicode 数字

    String.prototype.charCodeAt(index) 就是返回字符串中下标单个数值  对应的编码表的10进制表示数值 方法返回0到65535之间的整数,表示给定索引处的UTF-16代码 ...

  5. Linux shell脚本 基础

    一.shell中三个引号的用法 1.单引号:所见即所得 例如:var=123 var2='${var}123' echo var2 var2结果为${var}123 2.双引号:输出引号中的内容,若存 ...

  6. mysql自定义函数初始化数据:init_data()

    DELIMITER $$ USE `local_hnyz`$$ DROP FUNCTION IF EXISTS `init_data`$$ CREATE DEFINER=`root`@`localho ...

  7. BTree非递归

    preorder void PreOrder(BTNode* b) { BTNode* p = b; SqStack* st; InitStack(st); if (b != NULL) { Push ...

  8. AI大火之下智能手机行业能适应这一风口吗?

    今年智能手机行业的变化,实在是让人摸不到头脑.一方面是智能手机厂商依然在拿出各种具有噱头的产品,仿佛整个市场还依然热火朝天.但在另一方面,智能手机出货量却出现大幅下滑.据中国信息通信研究院发布的数据显 ...

  9. 有关于i++,i=i++等符号的笔记

    最近在看一些基础知识,发现自己以前忽略掉了很多东西,而这些东西恰恰是面试笔试中最常考到的 1.i=i+1 这个是最简单,最明了的一个表达式 2.有关于i++和++i的区别 i++和++i都是代表i=i ...

  10. 39)PHP,选取数据库中的两列

    首先是我的文件关系: 我的b.php是主php文件,BBB.php是配置文件,login.html是显示文件, b.php文件代码: <?php /** * Created by PhpStor ...