博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HttpClient-get请求/Post请求/Post-Json/Header
阅读量:5324 次
发布时间:2019-06-14

本文共 8694 字,大约阅读时间需要 28 分钟。

1、Pom文件添加httpClient 依赖

org.apache.httpcomponents
httpclient
4.5.5

 

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 = 0; 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", "1");        List
paramList = new ArrayList
(); 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() == 200) { // 读取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() == 201) {                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, 404, "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

 

转载于:https://www.cnblogs.com/zhou-test/p/9993438.html

你可能感兴趣的文章
使用GIT的失败过程
查看>>
Unity3d 协程的注意问题(新手须注意,老手须加勉)
查看>>
python爬虫学习(10) —— 专利检索DEMO
查看>>
日历 java方法实现
查看>>
Integer值判断是否相等问题
查看>>
实验中心服务器配置记录
查看>>
js数组去重
查看>>
UIView 设置背景图片
查看>>
$2018/8/15 = Day \ \ 1$杂题整理
查看>>
SpringBoot整合ActiveMQ
查看>>
[PCB设计] 2、畸形PCB板子的制作核心——AD14导入dwg格式文件的方法
查看>>
[每日电路图] 5、心率检测电路设计详解——送给想了解心率计的小白(博主推荐)...
查看>>
C#对 Dictionary进行排序 转
查看>>
51nod 1563 坐标轴上的最大团(今日gg模拟第一题) | 线段覆盖 贪心 思维题
查看>>
C#捕捉异常try catch finally throw(一)
查看>>
POJ-3683-Priest John's Busiest Day(2-sat)
查看>>
asp.net生成高质量缩略图通用函数(c#代码),支持多种生成方式
查看>>
使用R语言-操作data.frame
查看>>
文件系统管理
查看>>
[导入]古装武侠剧《神农碧血刀》全20集
查看>>