遇一山,过一山,处处有风景;只要勇敢向前,一路尽是繁花盛开。 | (点击查看→)【测试干货】python/java自动化、持续集成、性能、测开、简历、笔试面试等

HttpClient的使用(get、post请求)

 

添加依赖

HttpClient是java提供的与服务端http接口进行交互的库

方式一:

下载:https://hc.apache.org/downloads.cgi

选择二进制zip包

然后解压

 

如果是idea,把lib目录加入到Libraries中,如果是eclipse,lib目录复制到项目下,Build Path --> Add to Build Path

 

方式二:添加pom依赖

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

  

get请求

 

 

 

package com.qzcsbj;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
public class HttpGetRequest {
    public static void main(String[] args) {
        String url = "http://127.0.0.1:9999/download";
        String fname = "qzcsbj.txt";
        Map<String, String> params = new HashMap<String, String>();
        params.put("fname", fname);
        String res = getRequest(url, params);
        System.out.println("获取到的结果为:" + res);

    }
    public static String getRequest(String url, Map<String,String> params){
        String res = "";
        boolean flag = true;
        Set<String> keys = params.keySet();
        for (String key : keys) {
            if (flag){
                url += "?" + key + "=" + params.get(key);
                flag = false;
            }else {
                url += "&" + key + "=" + params.get(key);
            }
        }
        HttpGet httpGet = new HttpGet(url);
        HttpClient httpClient = HttpClients.createDefault();

        try {
            HttpResponse response = httpClient.execute(httpGet);
            res = EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
}

 

 

post请求

k-v

 

 

package com.qzcsbj;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
public class HttpPostRequest {
    public static void main(String[] args) {
        String url = "http://127.0.0.1:9999/login";
        HashMap<String, String> params = new HashMap<String, String>();
        String username = "qzcsbj";
        String password = "123456";
        params.put("username", username);
        params.put("password", password);
        String res = postRequest(url, params);
        System.out.println("获取到的结果为:" + res);
    }

    public static String postRequest(String url, Map<String,String> params){
        String res = "";
        HttpPost httpPost = new HttpPost(url);
        ArrayList<BasicNameValuePair> basicNameValuePairs = new ArrayList<BasicNameValuePair>();
        Set<String> keys = params.keySet();
        for (String key : keys) {
            basicNameValuePairs.add(new BasicNameValuePair(key,params.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(basicNameValuePairs,"utf-8"));
            HttpClient httpClient = HttpClients.createDefault();
            HttpResponse httpResponse = httpClient.execute(httpPost);
            res = EntityUtils.toString(httpResponse.getEntity());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
}

  

 

json

package com.qzcsbj;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.Set;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
public class Test {
    // 声明为静态方法,方便调用
    public static String postRequest(String url, JSONObject jsonObject, JSONObject headers){
        String res = "";
        HttpPost httpPost = new HttpPost(url);
        // 通过形参设置请求头
        Set<String> headerkeys = headers.keySet();
        for (String headerkey : headerkeys) {
            httpPost.addHeader(headerkey.trim(),headers.getString(headerkey).trim());
        }

        // 发送 json 类型数据
        httpPost.setEntity(new StringEntity(jsonObject.toString(),"UTF-8"));

        HttpClient httpClient = HttpClients.createDefault();
        // 发送请求
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpPost);
            System.out.println("状态码:" + httpResponse.getStatusLine().getStatusCode());
            res = EntityUtils.toString(httpResponse.getEntity());
            // res = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return res;
    }

    // 测试方法
    public static void main(String[] args) {
        // post:json
        String url2 = "http://127.0.0.1:9999/login";
        String parameters = "{\"username\":\"qzcsbj\",\"password\":\"123456\"}";
        String headers = "{\"Content-Type\":\"application/json\"}";
        JSONObject paramJsonObject = JSONObject.parseObject(parameters);
        JSONObject headersJsonObject = JSONObject.parseObject(headers);
        String res2 = postRequest(url2, paramJsonObject,headersJsonObject);
        System.out.println("获取到的结果为:" + res2);
    }
}

 

 

 

 

【bak】

原文会持续更新,原文地址:https://www.cnblogs.com/uncleyong/p/15867745.html

 

posted @ 2022-02-07 18:05  全栈测试笔记  阅读(1301)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end