HttpClient POST/SET方法

前言:

网络API接口:https://api.apiopen.top/searchMusic

此API接口返回类型为JSON格式类型

GET:从指定资源请求数据

POST:向指定资源提交要被处理的数据

GET与POST的区别:

①GET在浏览器回退时是无害的,而POST会再次提交请求。

②GET只支持URL编码。

③GET参数通过URL传递,参数直接暴露在URL中会泄露信息,POST通过Request body传递不会有这样的问题。

④GET请求在URL中传递参数有长度限制,POST没有长度限制。

⑤对POST请求会险发送Header,服务器相应成功,在发送Date,服务器再次响应,需响应两次。GET会把Header与Date一起发送到服务端,服务器只响应一次。

一、POST方法

创建POST方法类

 1 package com.HttpClient.Test;
 2
 3 import java.io.IOException;
 4 import java.util.ArrayList;
 5
 6 import org.apache.http.HttpEntity;
 7 import org.apache.http.HttpHost;
 8 import org.apache.http.NameValuePair;
 9 import org.apache.http.client.ClientProtocolException;
10 import org.apache.http.client.config.RequestConfig;
11 import org.apache.http.client.entity.UrlEncodedFormEntity;
12 import org.apache.http.client.methods.CloseableHttpResponse;
13 import org.apache.http.client.methods.HttpPost;
14 import org.apache.http.impl.client.CloseableHttpClient;
15 import org.apache.http.impl.client.HttpClientBuilder;
16 import org.apache.http.util.EntityUtils;
17
18 import com.HttpClient.jiexi.HttpClient_jiexi;
19
20 public class HttpClient_post {
21
22     private String entityStr;
23     HttpClient_jiexi JSONTOOL = new HttpClient_jiexi();
24
25     //封装POST方法
26     public String post(String POST_URL,ArrayList<NameValuePair> list) {
27
28         try {
29             //把参数放入请求体中
30             UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
31             CloseableHttpClient httpClient = HttpClientBuilder.create().build();
32             HttpPost httpPost = new HttpPost(POST_URL);
33             httpPost.setEntity(entityParam);
34             //发起请求
35             CloseableHttpResponse response = httpClient.execute(httpPost);
36             //获取返回状态,并判断是否连接成功。
37             if (response.getStatusLine().getStatusCode()==200) {
38                 System.out.println("连接成功");
39             } else {
40                 System.out.println("连接异常");
41             }
42             // 获得响应的实体对象
43             HttpEntity entity = response.getEntity();
44
45             //转换成字符串
46             entityStr = EntityUtils.toString(entity, "UTF-8");
47             //关闭请求
48             httpClient.close();
49
50         } catch (ClientProtocolException e) {
51             System.err.println("Http协议异常");
52             e.printStackTrace();
53         } catch (IOException e) {
54             System.err.println("IO异常");
55             e.printStackTrace();
56         }
57         return entityStr;
58     }
59
60 }

调用POST方法类

 1 package com.HttpClient.Test;
 2
 3 import java.util.ArrayList;
 4 import org.apache.http.NameValuePair;
 5 import org.apache.http.message.BasicNameValuePair;
 6 import org.json.JSONException;
 7 import org.testng.annotations.Test;
 8
 9 public class HttpClient_case1 {
10
11     HttpClient_post post = new HttpClient_post();
12     private String POST_URL = "https://api.apiopen.top/searchMusic";
13     private String entity;
14     private ArrayList<NameValuePair> list;
15
16     @Test
17     public void test1() {
18             // 构造list集合,并添加参数
19             BasicNameValuePair basicNameValuePair = new BasicNameValuePair("name", "十年");
20             list = new ArrayList<>();
21             list.add(basicNameValuePair);
22             // 执行请求,需要传入URL与参数
23             entity = post.post(POST_URL,list);
24             System.out.println(entity);
25     }
26
27 }

二、SET方法

创建SET方法类

package com.HttpClient.Test;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClient_set {

    public String entityStr ;
    public CloseableHttpResponse response ;

    public String set(String GET_URL,ArrayList<NameValuePair> list) throws URISyntaxException{try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            URIBuilder uriBuilder = new URIBuilder(GET_URL);
            uriBuilder.setParameters(list);
            //根据带参数的URI对象构建GET请求对象
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            //执行请求
            response = httpClient.execute(httpGet);
            //获得响应的实体对象
            HttpEntity entity = response.getEntity();
            //转换成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");

            //关闭请求
            httpClient.close();
        } catch (ClientProtocolException e) {
            System.err.println("Http协议异常");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO异常");
            e.printStackTrace();
        }
        return entityStr;

    }

}

调用SET方法类

package com.HttpClient.Test;

import java.net.URISyntaxException;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.testng.annotations.Test;

public class HttpClient_case1 {

    HttpClient_set set = new HttpClient_set();
    private String SET_URL = "https://api.apiopen.top/searchMusic";
    private String entity;
    private ArrayList<NameValuePair> list;

    @Test
    public void test1() throws URISyntaxException {
            // 构造list集合
            BasicNameValuePair basicNameValuePair = new BasicNameValuePair("name", "十年");
            list = new ArrayList<>();
            list.add(basicNameValuePair);
            // 执行请求,需要传入URL与参数
            entity = set.set(SET_URL, list);
            System.out.println(entity);

    }

}

原文地址:https://www.cnblogs.com/yogouo/p/11949355.html

时间: 2024-10-05 23:25:08

HttpClient POST/SET方法的相关文章

Android之HttpClient的使用方法

HttpClient的使用方法 实例解析:HttpClient的get,post的数据传输 package com.example.httpclient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URLEncoder; import org.apache.http.HttpEntity; import org.apach

Android HttpClient基本使用方法

GET 方式 //先将参数放入List,再对参数进行URL编码 List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>(); params.add(new BasicNameValuePair("param1", "中国")); params.add(new BasicNameValuePair("param2", "value2&

HttpClient的使用方法

使用httpClient发送请求.接收响应很简单.一般需要以下几个步骤. 第一:创建HttpClient对象: 第二:创建请求方法的实例,并指定请求URL.如果要发送GET请求,创建HttpGet对象,如果要发送POST请求,创建HTtppost对象. 第三步:如果需要发送请求参数,可调用HttpGet.HttpPost共同的setParams(httpParams params)方法来添加请求参数:对于HttpPost对象而言,也可调用setEntity(httpEntity entity)方

HttpClient 4 使用方法的几个例子(代理,StringEntity字符串数据,文件上传)(转载)

1,HttpClient读取页面的使用例子: package com.laozizhu.apache.httpclient; import java.net.Socket; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apa

httpclient之post 方法(参数为json类型)

package httpclient;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; import org.apache.

.netcore 3.1高性能微服务架构:封装调用外部服务的接口方法--HttpClient客户端思路分析

众所周知,微服务架构是由一众微服务组成,项目中调用其他微服务接口更是常见的操作.为了便于调用外部接口,我们的常用思路一般都是封装一个外部接口的客户端,使用时候直接调用相应的方法.webservice或WCF的做法就是引用服务,自动生成客户端.在webapi2.0里,我们都会手动封装一个静态类.那么在.netcore3.1的微服务时代,我们该如何处理这个问题呢? ----思路都是一样的,封装一个外部服务,并且使用依赖注入和 HttpFactory工厂等.netcore特有的方式提升性能.接下来我们

httpclient的几种请求URL的方式

一.httpclient项目有两种使用方式.一种是commons项目,这一个就只更新到3.1版本了.现在挪到了HttpComponents子项目下了,这里重点讲解HttpComponents下面的httpclient的使用方式. 二.加入jar包 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <ver

接口测试(二)—HttpClient

使用HttpClient进行接口测试,所需要使用的相关代码 HttpClient进行接口测试所需jar包:httpclient.jar.httpcore.jar.commons-logging.jarGet请求://创建httpclient对象CloseableHttpClient httpClient = HttpClients.createDefault();//如果发送的是GET请求,创建HttpGet对象HttpGet httpget = new HttpGet("http://www.

HttpClient使用笔记

四步走: 1.先创建一个DefaultHttpClient的实例 HttpClient httpClient=new DefaultHttpClient(); 2.发送GET请求: 先创建一个HttpGet对象,传入目标的网络地址,然后调用HttpClient的execute()方法即可: HttpGet HttpGet=new HttpGet(“http://www.baidu.com”); httpClient.execute(httpGet); 3.返回响应实体↓ HttpResponse