欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpClient实现Http+xml接口调用

程序员文章站 2022-07-13 12:55:45
...
HttpClient示例
package web;

import java.io.File;
import java.io.FileInputStream;
import java.util.Map;

import javax.security.auth.login.LoginException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClientTest
{

    /** <一句话功能简述>
     * <功能详细描述>
     * @param args
     * @see [类、类#方法、类#成员]
     */
    public static void main(String[] args)
    {
        String checkTokenUrl="http://localhost:8888/test4A";//接口地址
        HttpClient httpClient = null;
        PostMethod  postMethod  = null;
        try
        {
            httpClient = new HttpClient();
            //设置超时时间
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);
            postMethod  = new PostMethod(checkTokenUrl);

            //组装xml报文
             String xmlStr="";
           //TODO

            postMethod.setRequestBody(xmlStr);

            //postMethod.setRequestBody(new NameValuePair[]{name});
            // 设置成了默认的恢复策略,在发生异常时候将自动重试3次,在这里你也可以设置成自定义的恢复策略
            postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

            // 执行getMethod

            int statusCode = httpClient.executeMethod(postMethod);

            if (statusCode != HttpStatus.SC_OK)
            {
                System.err.println("Call 4A check token method failed: " + postMethod.getStatusLine());
            }

            String rsp = postMethod.getResponseBodyAsString();
            System.out.println(rsp);

            // 解析应答报文
            //TODO

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (postMethod != null)
            {
                postMethod.releaseConnection();
            }
        }
    }

}