访问rest接口

本文介绍了一个使用Java实现的HTTP客户端类,该类通过POST方法发送JSON格式的数据,并接收响应。文章详细展示了如何导入必要的jar包,如commons-beanutils、commons-collections等,并提供了完整的类定义代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导入jar包:

commons-beanutils-1.7.0.jar
commons-collections-3.1.jar
commons-lang-2.5.jar
commons-logging.jar
ezmorph-1.0.3.jar
json-lib-2.4-jdk15.jar
httpclient-4.3.2.jar
httpcore-4.3.2.jar

代码:


import java.io.IOException;
import java.nio.charset.Charset;

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class AccessRest {
    private static AccessRest accessRest = null;
    private String apiURL = "";
    private HttpClient httpClient = null;
    private HttpPost method = null;

    /**
     * 默认构造方法
     */
    private AccessRest() {
    }

    /**
     * 含参构造方法
     * 
     * @param url
     */
    private AccessRest(String url) {
        if (null != url && !"".equals(url)) {
            this.apiURL = url;
        }
        if (null != apiURL && !"".equals(apiURL)) {
            httpClient = new DefaultHttpClient();
            method = new HttpPost(apiURL);
        }
    }

    /**
     * 单例方法
     * @param url
     * @return
     */
    public static AccessRest getInstance(String url) {
        if (accessRest == null) {
            accessRest = new AccessRest(url);
        }
        return accessRest;
    }

    /**
     * 设置URL
     * @param url
     */
    public void setAPIURL(String url){
        this.apiURL=url;
        if (null != apiURL && !"".equals(apiURL)) {
            httpClient = new DefaultHttpClient();
            method = new HttpPost(apiURL);
        }
    }

    /**
     * JSON内容格式的POST请求
     * @param params
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public String JSONToPost(String token,String params) throws ClientProtocolException, IOException {
        //添加post请求报文header,格式为JSON
        method.setHeader("Content-type","application/json; charset=utf-8");
        method.setHeader("Accept", "application/json");
        //添加JSON格式报文内容
        method.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
        //访问接口
        HttpResponse response = httpClient.execute(method);
        //构造返回值
        JSONObject message = new JSONObject();
        //添加状态码
        message.put("StatusCode", String.valueOf(response.getStatusLine().getStatusCode()));
        //添加内容
        message.put("Message", EntityUtils.toString(response.getEntity()));
        return message.toString();
    }

    /**
     * 普通参数访问网址
     * @param params
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public String urlencodedToPost(String params) throws ClientProtocolException, IOException{
        //设置请求报文头
        method.setHeader("Content-type","application/json; charset=utf-8");
        method.setHeader("Accept", "application/x-www-form-urlencoded");
        //设置请求参数
        method.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
        //访问接口
        HttpResponse response = httpClient.execute(method);
        //构造返回值
        JSONObject message = new JSONObject();
        //添加状态码
        message.put("StatusCode", String.valueOf(response.getStatusLine().getStatusCode()));
        //添加内容
        message.put("Message", EntityUtils.toString(response.getEntity()));
        return message.toString();
    }
}
restful restful所需要的jar ========================================= Restlet, a RESTful Web framework for Java ========================================= http://www.restlet.org ----------------------------------------- Native REST support * Core REST concepts have equivalent Java classes (UniformInterface, Resource, Representation, Connector for example). * Suitable for both client-side and server-side web applications. The innovation is that that it uses the same API, reducing the learning curve and the software footprint. * Restlet-GWT module available, letting you leverage the Restlet API from within any Web browser, without plugins. * Concept of "URIs as UI" supported based on the URI Templates standard. This results in a very flexible yet simple routing with automatic extraction of URI variables into request attributes. * Tunneling service lets browsers issue any HTTP method (PUT, DELETE, MOVE, etc.) through a simple HTTP POST. This service is transparent for Restlet applications. Complete Web Server * Static file serving similar to Apache HTTP Server, with metadata association based on file extensions. * Transparent content negotiation based on client preferences. * Conditional requests automatically supported for resources. * Remote edition of files based on PUT and DELETE methods (aka mini-WebDAV mode). * Decoder service transparently decodes compressed or encoded input representations. This service is transparent for Restlet applications. * Log service writes all accesses to your applications in a standard Web log file. The log format follows the W3C Extended Log File Format and is fully customizable. * Powerful URI based redirection support similar to Apache Rewrite module. Available Connectors * Multiple server HTTP connectors available, based on either Mortbay's Jetty or the Simple framework or Grizzly NIO framework. * AJP server connector available to let you plug behind an Apache HTT
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值