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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM