【Java】Apache HttpClient使用说明备忘录

创建Maven项目

请按照以下文章的参考,创建一个Maven项目。

mvn archetype:generate \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  -DinteractiveMode=false \
  -DgroupId=com.sample \
  -DartifactId=http-client-sample

编辑pom.xml文件

通过编辑pom.xml文件,将Apache HttpClient导入项目中。
同时,参考以下文章,添加配置以便通过mvn命令执行并生成可执行的JAR文件。

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample</groupId>
  <artifactId>http-client-sample</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>http-client-sample</name>
  <url>http://maven.apache.org</url>
  <properties>
    <java.version>1.8</java.version>
    <maven.compiler.target>${java.version}</maven.compiler.target>
    <maven.compiler.source>${java.version}</maven.compiler.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.13</version>
    </dependency>
    <!--
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.14.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.14.1</version>
    </dependency>
    -->
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <mainClass>com.sample.App</mainClass>
        </configuration>
      </plugin>
      <!-- 実行可能jarファイル用のプラグイン -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.3.0</version>
        <configuration>
          <finalName>sample</finalName>
          <descriptorRefs>
            <!-- 依存するリソースをすべてjarに同梱する -->
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
          <archive>
            <manifest>
              <mainClass>com.sample.App</mainClass>
            </manifest>
          </archive>
        </configuration>
        <executions>
          <execution>
            <!-- idタグは任意の文字列であれば何でもよい -->
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

Java代码

我会参考以下的文章,并编写一个程序来进行GET请求和POST请求。

package com.sample;

public class App
{
    public static void main( String[] args ) {
        Client clinet = new Client("testId");
        clinet.exec();
    }
}
package com.sample;

import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
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.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Client {
    // private static final Logger logger = LogManager.getLogger(MethodHandles.lookup().lookupClass());
    private String id;

    public Client(String id) {
        this.id = id;
    }

    public void exec() {
        // Cookieを扱うための準備
        BasicCookieStore cookieStore = new BasicCookieStore();

        try ( CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); ) {
            RequestConfig config = RequestConfig.custom()
                .setSocketTimeout(3000)
                .setConnectTimeout(3000)
                .build();

            // Cookieを設定
            HttpGet httpGet = new HttpGet("https://httpbin.org/cookies/set?key=" + this.id);
            httpGet.setConfig(config);

            // GETリクエストの実行
            try ( CloseableHttpResponse httpResponse = httpClient.execute(httpGet); ) {
                if ( httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK ) {
                    System.out.println("Cookie設定");
                    System.out.println(EntityUtils.toString(httpResponse.getEntity()));
                } else {
                    System.out.println("エラー: " + httpResponse.getStatusLine().getStatusCode());
                    return;
                }
            } catch (Exception e) {
                throw e;
            }

            // JSONをPost
            HttpPost httpPost = new HttpPost("https://httpbin.org/anything");

            // 文字コードを指定
            httpPost.setHeader("Content-type", "application/json; charset=UTF-8");
            // PostするJSON文字列のセット
            String json = "{\"name\":\"foo\", \"mail\":\"bar\"}";
            StringEntity entity = new StringEntity(json, "UTF-8");
            httpPost.setEntity(entity);

            // POSTリクエストの実行
            try ( CloseableHttpResponse httpResponse = httpClient.execute(httpPost); ) {
                if( httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK ) {
                    System.out.println("Post実行");
                    System.out.println(EntityUtils.toString(httpResponse.getEntity()));
                } else {
                    System.out.println("エラー: " + httpResponse.getStatusLine().getStatusCode());
                    return;
                }
            } catch (Exception e) {
                throw e;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

我們使用了一個名為httpbin的網絡服務作為API的端點。

进行

在pom.xml的位置运行以下命令。

mvn compile
mvn exec:java

创建和执行可运行的JAR文件,请使用以下命令。

mvn install
cd target/
java -jar sample-jar-with-dependencies.jar

请参考

广告
将在 10 秒后关闭
bannerAds