HTTPClient调用---org.apache.commons.httpclient

package com.sinoservices.edi.http;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 * 基于Apache Httpclient3.X实现
 * 
 * @版权:SINOSERVICES 版权所有 (c) 2013
 * @author:Mars
 * @version Revision 1.0.0
 * @email:[email protected]
 * @see:
 * @创建日期:2017年2月23日
 * @功能说明:
 * @begin
 * @修改记录:
 * @修改后版本 修改人 修改内容
 * @2017年2月23日 Mars 创建
 * @end
 */
public class HttpClientUtil {

    public static void clientTestUtil() throws Exception {

        String httpServerURL = " http://127.0.0.1:8889/server";
        String body = "this is my test body...";

        SimpleHttpConnectionManager connectionManager = new SimpleHttpConnectionManager(true);
        // 连接超时,单位毫秒/* 连接超时 */
        connectionManager.getParams().setConnectionTimeout(60 * 1000);
        // 读取超时,单位毫秒/* 请求超时 */
        connectionManager.getParams().setSoTimeout(60000);

        // 设置获取内容编码
        connectionManager.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        HttpClient client = new HttpClient(new HttpClientParams(), connectionManager);

        PostMethod post = new PostMethod(httpServerURL);
        // 设置请求参数的编码
        post.getParams().setContentCharset("UTF-8");

        // 服务端完成返回后,主动关闭链接
        post.setRequestHeader("Connection", "close");
        post.setRequestHeader("Content-Type", "text/plain;chartset=UTF-8");
        StringRequestEntity requestEntity;
        requestEntity = new StringRequestEntity(body, "application/x-www-form-urlencoded", "UTF-8");
        post.setRequestEntity(requestEntity);
        int sendStatus = client.executeMethod(post);
        System.err.println("Notice:if sendStatus is 200,post is success.");
        if (sendStatus == HttpStatus.SC_OK) {
            String responseResult = post.getResponseBodyAsString();
            System.err.println(responseResult);
        }
        // 释放链接
        if (post != null) {
            post.releaseConnection();
        }

        // 关闭链接
        if (connectionManager != null) {
            connectionManager.shutdown();
        }

    }

    public static void main(String[] args) throws Exception {
        clientTestUtil();
    }
}

你可能感兴趣的:(HTTP)