java HttpClient学习笔记

配置

  1. Apache HttpClient 5.0

  2. fastjson

下载并解压

范例代码

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;

public class QuickStart {
     
	private static void login(CloseableHttpClient httpclient) throws Exception {
     
		System.out.println("login:");

        final HttpPut httpPost = new HttpPut("http://192.168.1.106/cgi-bin/entry.cgi/system/login");
        final List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("sUserName", "admin"));
        nvps.add(new BasicNameValuePair("sUserName", "admin"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
		httpPost.setHeader("Connection", "keep-alive");
		//httpPost.setHeader("Content-Length", "44");
		httpPost.setHeader("Accept", "application/json, text/plain, */*");
		httpPost.setHeader("Authorization", "Bearer undefined");
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36");
		httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
		httpPost.setHeader("Accept-Encoding", "gzip, deflate");
		httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
		
		String parameter = "{ \"sUserName\":\"admin\", \"sPassword\":\"admin\" }"; //JSON.toJSONString(param);  
        StringEntity se = null;
        try {
     
            System.out.println(parameter);
            se = new StringEntity(parameter, ContentType.APPLICATION_JSON);
        } catch (Exception e) {
     
            e.printStackTrace();
        }
		
        //se.setContentType("applicaiton/json");
        httpPost.setEntity(se);
		
		try (final CloseableHttpResponse response2 = httpclient.execute(httpPost)) {
     
            System.out.println(response2.getCode() + "--" + response2.getReasonPhrase());
            final HttpEntity entity2 = response2.getEntity();
			
			System.out.println(EntityUtils.toString(entity2));
			
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity2);
        }
	}

	private static void testPost(CloseableHttpClient httpclient) throws Exception {
     
		System.out.println("http post:");

        final HttpPost httpPost = new HttpPost("http://httpbin.org/post");
        final List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("username", "vip"));
        nvps.add(new BasicNameValuePair("password", "secret"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));

        try (final CloseableHttpResponse response2 = httpclient.execute(httpPost)) {
     
            System.out.println(response2.getCode() + "--" + response2.getReasonPhrase());
            final HttpEntity entity2 = response2.getEntity();
			
			System.out.println(EntityUtils.toString(entity2));
			
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity2);
        }
	}
	
	private static void testGet(CloseableHttpClient httpclient) throws Exception {
     
		System.out.println("http get:");
			
        final HttpGet httpGet = new HttpGet("http://httpbin.org/get");
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try (final CloseableHttpResponse response1 = httpclient.execute(httpGet)) {
     
            System.out.println(response1.getCode() + "--" + response1.getReasonPhrase());
            final HttpEntity entity1 = response1.getEntity();
			
			System.out.println(EntityUtils.toString(entity1));
			
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity1);
        }
	}

    public static void main(final String[] args) throws Exception {
     
		/*HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, CHARSET);
		HttpProtocolParams.setUseExceptionContinue(params, true);
		HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36");*/

        try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
     
			login(httpclient);
        }
		catch(Exception e) {
     
			System.out.println(e.toString());
		}
    }

}

编译

set off

set HTTPCLIENT_LIB_DIR=D:/Java/httpcomponents-client-5.0.1/lib
set HTTPCLIENT_PKG=.;%HTTPCLIENT_LIB_DIR%/commons-cli-1.4.jar;%HTTPCLIENT_LIB_DIR%/commons-codec-1.13.jar;%HTTPCLIENT_LIB_DIR%/httpclient5-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpclient5-cache-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpclient5-fluent-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpclient5-testing-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpclient5-win-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpcore5-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpcore5-h2-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpcore5-reactive-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpcore5-testing-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/jna-5.2.0.jar;%HTTPCLIENT_LIB_DIR%/jna-platform-5.2.0.jar;%HTTPCLIENT_LIB_DIR%/reactive-streams-1.0.2.jar;%HTTPCLIENT_LIB_DIR%/rxjava-2.2.8.jar;%HTTPCLIENT_LIB_DIR%/slf4j-api-1.7.25.jar;%HTTPCLIENT_LIB_DIR%/fastjson-1.2.73.jar;

javac -encoding UTF-8 -classpath %HTTPCLIENT_PKG% -d ./ QuickStart.java

执行

set off

set HTTPCLIENT_LIB_DIR=D:/Java/httpcomponents-client-5.0.1/lib
set HTTPCLIENT_PKG=.;%HTTPCLIENT_LIB_DIR%/commons-cli-1.4.jar;%HTTPCLIENT_LIB_DIR%/commons-codec-1.13.jar;%HTTPCLIENT_LIB_DIR%/httpclient5-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpclient5-cache-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpclient5-fluent-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpclient5-testing-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpclient5-win-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpcore5-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpcore5-h2-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpcore5-reactive-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/httpcore5-testing-5.0.1.jar;%HTTPCLIENT_LIB_DIR%/jna-5.2.0.jar;%HTTPCLIENT_LIB_DIR%/jna-platform-5.2.0.jar;%HTTPCLIENT_LIB_DIR%/reactive-streams-1.0.2.jar;%HTTPCLIENT_LIB_DIR%/rxjava-2.2.8.jar;%HTTPCLIENT_LIB_DIR%/slf4j-api-1.7.25.jar;%HTTPCLIENT_LIB_DIR%/fastjson-1.2.73.jar;

java -cp %HTTPCLIENT_PKG% QuickStart

你可能感兴趣的:(JAVA,java)