Apache HttpComponents项目Get和Post简单使用

1、使用的库Apache HttpComponents

①httpcore(http://devdoc.net/apache/httpcomponents-core-4.4.1-javadoc/)


<dependency>
        <groupId>org.apache.httpcomponentsgroupId>
        <artifactId>httpcoreartifactId>
        <version>4.4.10version>
dependency>

②httpclient(http://devdoc.net/apache/httpcomponents-client-4.5-javadoc/)


<dependency>
        <groupId>org.apache.httpcomponentsgroupId>
        <artifactId>httpclientartifactId>
        <version>4.5.6version>
dependency>

③httpmime(http://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/index.html?overview-summary.html)


<dependency>
        <groupId>org.apache.httpcomponentsgroupId>
        <artifactId>httpmimeartifactId>
        <version>4.5.6version>
dependency>

2、httpGet示例

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

public class HttpComponentsGetTest {

    public static void main(String[] args) throws URISyntaxException {
    	
    	CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)   //设置连接超时时间
                .setConnectionRequestTimeout(5000) // 设置请求超时时间
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)//默认允许自动重定向
                .build();

        URI uri = new URI("http://localhost:80/test?account=你好&password=你不好");
        
        HttpGet httpGet = new HttpGet(uri);
        httpGet.setConfig(requestConfig);

        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if(httpResponse.getStatusLine().getStatusCode() == 200){
                //注意,重要的话只说一遍
                //不管你使用不使用entity,一定要获取输入流,然后关闭
                //不然,如果你这个程序不是立刻停止,接下来还要发送请求时就会发生请求池超时的错误
                //这个对于Get,Post都一样
                HttpEntity entity = httpResponse.getEntity();
                InputStream inputStream = entity.getContent();
                FileOutputStream fileOutputStream = new FileOutputStream(new File("E:/test.html"));
                fileOutputStream.write(inputStream.readAllBytes());
                inputStream.close();
                fileOutputStream.close();
                System.out.println("success");
            }else {
                System.out.println("返回异常");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3、HttpPost示例

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
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.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class HttpComponentsPostTest {

    public static void main(String[] args) {

        // 获取可关闭的 httpCilent
        CloseableHttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();

        // 配置超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000).setRedirectsEnabled(true).build();

        HttpPost httpPost = new HttpPost("http://localhost:80/test2");

        // 设置超时时间
        httpPost.setConfig(requestConfig);

        // 装配post请求参数
        List<BasicNameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("account", "你好")); // 请求参数
        list.add(new BasicNameValuePair("password", "你不好")); // 请求参数

        try {
            //如果要传输文件,需要使用org.apache.http.entity.mime.MultipartEntity
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
            httpPost.setEntity(entity);
            httpPost.setHeader("User-Agent", "HTTPie/0.9.2");

            HttpResponse httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() != 200) {
                System.out.println(httpResponse.getStatusLine().getStatusCode());
                throw new Exception("返回异常");
            }

            //注意,重要的话只说一遍
            //不管你使用不使用entity,一定要获取输入流,然后关闭
            //不然,如果你这个程序不是立刻停止,接下来还要发送请求时就会发生请求池超时的错误
            //这个对于Get,Post都一样
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream inputStream = httpEntity.getContent();
            FileOutputStream fileOutputStream = new FileOutputStream(new File("E:/test.html"));
            fileOutputStream.write(inputStream.readAllBytes());
            inputStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(计算机,java,网络,Apache,HttpComponents,HttpClient,java,网络)