httpclient发送http请求设置网络超时时间

一、发送的ApiClient方法
可以设置网络超时时间

/*** Eclipse Class Decompiler plugin, copyright (c) 2016 Chen Chao ([email protected]) ***/
package liaohui.api;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import liaohui.exception.ApiRequestException;
import net.sf.json.JSONObject;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class ApiClient {
    private static final int STATUS_200 = 200;
    private static Integer DEFAULT_CONNECT_TIMEOUT = Integer.valueOf(60000);

    private static Integer DEFAULT_READ_TIMEOUT = Integer.valueOf(60000);

    private static Integer DEFAULT_CONNECTION_REQUEST_TIMEOUT = Integer
            .valueOf(1000);

    private HttpClient httpclient = null;

    public static void setDefaultTimeOut(Integer connectTimeout,
            Integer readTimeout, Integer connectionRequestTimeout) {
        DEFAULT_CONNECT_TIMEOUT = connectTimeout;
        DEFAULT_READ_TIMEOUT = readTimeout;
        DEFAULT_CONNECTION_REQUEST_TIMEOUT = connectionRequestTimeout;
    }

    public static void setConnectionPoolMax(Integer maxTotal,
            Integer maxPerRoute) {
    }

    public ApiClient() {
        this.httpclient = new DefaultHttpClient();
    }

    public String postForm(String url, Map<String, String> params,
            Map<String, String> headers, Integer connTimeout,
            Integer readTimeout, Integer connectionRequestTimeout)
            throws ApiRequestException {
        List formParams = httpClientParamsConvert(params);
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams,
                Consts.UTF_8);
        return post(url, entity, headers, connTimeout, readTimeout,
                connectionRequestTimeout);
    }

    public String postForm(String url, Map<String, String> params)
            throws ApiRequestException {
        return postForm(url, params, null, null, null, null);
    }

    public String postJson(String url, JSONObject params,
            Map<String, String> headers, Integer connTimeout,
            Integer readTimeout, Integer connectionRequestTimeout)
            throws ApiRequestException {
        try {
            HttpEntity entity = new StringEntity(params.toString(), "UTF-8");
            return post(url, entity, headers, connTimeout, readTimeout,
                    connectionRequestTimeout);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new ApiRequestException(e.getMessage());
        }
    }

    public String postJson(String url, JSONObject params)
            throws ApiRequestException {
        return postJson(url, params, null, null, null, null);
    }

    public String post(String url, HttpEntity entity,
            Map<String, String> headers, Integer connTimeout,
            Integer readTimeout, Integer connectionRequestTimeout)
            throws ApiRequestException {
        String resBody = null;
        HttpPost post = new HttpPost(url);
        post.setEntity(entity);
        setTimeOut(post, connTimeout, readTimeout, connectionRequestTimeout);
        setHeader(headers, post);
        HttpResponse res = null;
        try {
            res = this.httpclient.execute(post);
            if (res.getStatusLine().getStatusCode() == 200)
                resBody = EntityUtils.toString(res.getEntity(), Consts.UTF_8);
            else
                throw new ApiRequestException("url:" + url + "\thttp 响应状态码为:"
                        + res.getStatusLine().getStatusCode());
        } catch (Exception e) {
        } finally {
            post.releaseConnection();
        }

        return resBody;
    }

    public String postFile(String url, File file, String fileParamName,
            Map<String, String> otherParams, Map<String, String> headers,
            Integer connTimeout, Integer readTimeout,
            Integer connectionRequestTimeout) throws ApiRequestException {
        HttpPost post = new HttpPost(url);
        BufferedReader bufReader = null;
        String resBody = null;
        try {
            MultipartEntity reqEntity = new MultipartEntity();
            if (otherParams != null) {
                Set keys = otherParams.keySet();
                Iterator it = keys.iterator();
                while (it.hasNext()) {
                    String paramName = (String) it.next();
                    reqEntity.addPart(paramName, new StringBody(
                            (String) otherParams.get(paramName)));
                }
            }
            reqEntity.addPart(fileParamName, new FileBody(file));
            post.setEntity(reqEntity);
            setTimeOut(post, connTimeout, readTimeout, connectionRequestTimeout);
            setHeader(headers, post);

            HttpResponse res = this.httpclient.execute(post);
            if (res.getStatusLine().getStatusCode() == 200) {
                resBody = EntityUtils.toString(res.getEntity(), Consts.UTF_8);
            } else
                throw new ApiRequestException("http 响应状态码为:"
                        + res.getStatusLine().getStatusCode());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            post.releaseConnection();
            post.abort();

            if (bufReader != null) {
                try {
                    bufReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resBody;
    }

    public String postFile(String url, File file, String fileParamName,
            Map<String, String> otherParams) throws ApiRequestException {
        return postFile(url, file, fileParamName, otherParams, null, null,
                null, null);
    }

    private List<NameValuePair> httpClientParamsConvert(
            Map<String, String> params) {
        List formParams = new ArrayList();

        Set<Entry<String, String>> entrySet = params.entrySet();
        for (Map.Entry entry : entrySet) {
            formParams.add(new BasicNameValuePair((String) entry.getKey(),
                    (String) entry.getValue()));
        }
        return formParams;
    }

    private void setHeader(Map<String, String> headers, HttpPost post) {
        if ((headers != null) && (!(headers.isEmpty())))
            for (Map.Entry entry : headers.entrySet())
                post.addHeader((String) entry.getKey(),
                        (String) entry.getValue());
    }

    private void setTimeOut(HttpPost post, Integer connTimeout,
            Integer readTimeout, Integer connectionRequestTimeout) {
        if (connTimeout == null) {
            connTimeout = DEFAULT_CONNECT_TIMEOUT;
        }
        if (readTimeout == null) {
            readTimeout = DEFAULT_READ_TIMEOUT;
        }
        if (connectionRequestTimeout == null) {
            connectionRequestTimeout = DEFAULT_CONNECTION_REQUEST_TIMEOUT;
        }

        this.httpclient.getParams().setParameter("http.connection.timeout",
                connTimeout);
        this.httpclient.getParams().setParameter("http.socket.timeout",
                readTimeout);
    }

    public static void main(String[] args) throws ApiRequestException {
        String url = "http://192.168.1.52:8080/sleep";
        Map params = new HashMap();

        ApiClient client = new ApiClient();
        try {
            long begin = System.currentTimeMillis();
            String res = client.postForm(url, params, null,
                    Integer.valueOf(4000), Integer.valueOf(4000), null);
            System.out.println("cost time="+String.valueOf(System.currentTimeMillis()-begin));
            System.out.println(res);
        } catch (ApiRequestException e) {
            System.out.println("exception:" + e.getMessage());
        }
    }
}

二、异常类

package liaohui.exception;

public class ApiRequestException extends Exception {
    private static final long serialVersionUID = 6071151941711591989L;

    public ApiRequestException() {
    }

    public ApiRequestException(String message) {
        super(message);
    }
}

三、maven依赖pom.xml文件

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.liaohui.cn</groupId>
  <artifactId>liaohui</artifactId>
  <version>0.0.1-SNAPSHOT</version>


<name>api-client</name>
  <url>http://maven.apache.org</url>

  <properties>
    <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>
    <!-- httpclient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.2.6</version>
    </dependency>
    <!-- http-mime -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.2.6</version>
    </dependency> 
    <!-- json -->
    <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
        <classifier>jdk15</classifier>
    </dependency>
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.6</version>
    </dependency>

  </dependencies>
  <distributionManagement>
    <repository>
        <id>thirdparty</id> 
        <name>Thirdparty Repository</name> 
        <url>http://192.168.1.7:8081/nexus/content/repositories/thirdparty/</url> 
    </repository>
    <snapshotRepository>
        <id>nexus-snapshots</id> 
        <name>Snapshots Repository</name> 
        <url>http://192.168.1.7:8081/nexus/content/repositories/snapshots/</url> 
    </snapshotRepository>
  </distributionManagement>

</project>

项目结构
这里写图片描述

猜你喜欢

转载自blog.csdn.net/lh9898/article/details/79298609