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

java调用Restful接口的三种方法

程序员文章站 2022-07-27 22:06:32
目录2,httpurlconnection实现3.httpclient实现4.spring的resttemplate1,基本介绍restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比...

1,基本介绍

restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多,

  本次介绍三种:

    1.httpurlconnection实现

    2.httpclient实现

    3.spring的resttemplate     

2,httpurlconnection实现

@controller
public class restfulaction {

    @autowired
    private userservice userservice;
    // 修改
    @requestmapping(value = "put/{param}", method = requestmethod.put)
    public @responsebody string put(@pathvariable string param) {
        return "put:" + param;
    }
    // 新增
    @requestmapping(value = "post/{param}", method = requestmethod.post)
    public @responsebody string post(@pathvariable string param,string id,string name) {
        system.out.println("id:"+id);
        system.out.println("name:"+name);
        return "post:" + param;
    }
    // 删除
    @requestmapping(value = "delete/{param}", method = requestmethod.delete)
    public @responsebody string delete(@pathvariable string param) {
        return "delete:" + param;
    }
    // 查找
    @requestmapping(value = "get/{param}", method = requestmethod.get)
    public @responsebody string get(@pathvariable string param) {
        return "get:" + param;
    }
    // httpurlconnection 方式调用restful接口
    // 调用接口
    @requestmapping(value = "dealcon/{param}")
    public @responsebody string dealcon(@pathvariable string param) {
        try {
            string url = "http://localhost:8080/tao-manager-web/";
            url+=(param+"/xxx");
            url restserviceurl = new url(url);
            httpurlconnection httpconnection = (httpurlconnection) restserviceurl
                    .openconnection();
            //param 输入小写,转换成 get post delete put 
            httpconnection.setrequestmethod(param.touppercase());
//            httpconnection.setrequestproperty("accept", "application/json");
            if("post".equals(param)){
                //打开输出开关
                httpconnection.setdooutput(true);
//                httpconnection.setdoinput(true);

                //传递参数
                string input = "&id="+ urlencoder.encode("abc", "utf-8");
                input+="&name="+ urlencoder.encode("啊啊啊", "utf-8");
                outputstream outputstream = httpconnection.getoutputstream();
                outputstream.write(input.getbytes());
                outputstream.flush();
            }
            if (httpconnection.getresponsecode() != 200) {
                throw new runtimeexception(
                        "http get request failed with error code : "
                                + httpconnection.getresponsecode());
            }
            bufferedreader responsebuffer = new bufferedreader(
                    new inputstreamreader((httpconnection.getinputstream())));
            string output;
            system.out.println("output from server:  \n");
            while ((output = responsebuffer.readline()) != null) {
                system.out.println(output);
            }
            httpconnection.disconnect();
        } catch (malformedurlexception e) {
            e.printstacktrace();
        } catch (ioexception e) {
            e.printstacktrace();
        }
        return "success";
    }
}

3.httpclient实现

package com.taozhiye.controller;
import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.namevaluepair;
import org.apache.http.client.httpclient;
import org.apache.http.client.entity.urlencodedformentity;
import org.apache.http.client.methods.httpdelete;
import org.apache.http.client.methods.httpget;
import org.apache.http.client.methods.httppost;
import org.apache.http.client.methods.httpput;
import org.apache.http.impl.client.httpclients;
import org.apache.http.message.basicnamevaluepair;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.responsebody;
import com.fasterxml.jackson.databind.objectmapper;
import com.taozhiye.entity.user;
import com.taozhiye.service.userservice;
import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.net.httpurlconnection;
import java.net.malformedurlexception;
import java.net.url;
import java.net.urlencoder;
import java.util.arraylist;
import java.util.list;

@controller
public class restfulaction {  
    @autowired
    private userservice userservice;
    // 修改
    @requestmapping(value = "put/{param}", method = requestmethod.put)
    public @responsebody string put(@pathvariable string param) {
        return "put:" + param;
    }
    // 新增
    @requestmapping(value = "post/{param}", method = requestmethod.post)
    public @responsebody user post(@pathvariable string param,string id,string name) {
        user u = new user();
        system.out.println(id);
        system.out.println(name);
        u.setname(id);
        u.setpassword(name);
        u.setemail(id);
        u.setusername(name);
        return u;
    }    
    // 删除
    @requestmapping(value = "delete/{param}", method = requestmethod.delete)
    public @responsebody string delete(@pathvariable string param) {
        return "delete:" + param;
    }
    // 查找
    @requestmapping(value = "get/{param}", method = requestmethod.get)
    public @responsebody user get(@pathvariable string param) {
        user u = new user();
        u.setname(param);
        u.setpassword(param);
        u.setemail(param);
        u.setusername("爱爱啊");
        return u;
    }
    @requestmapping(value = "dealcon2/{param}")
    public @responsebody user dealcon2(@pathvariable string param) {
        user user = null;
        try {
            httpclient client = httpclients.createdefault();
            if("get".equals(param)){
                httpget request = new httpget("http://localhost:8080/tao-manager-web/get/"
                        +"啊啊啊");
                request.setheader("accept", "application/json");
                httpresponse response = client.execute(request);
                httpentity entity = response.getentity();
                objectmapper mapper = new objectmapper();
                user = mapper.readvalue(entity.getcontent(), user.class);
            }else if("post".equals(param)){
                httppost request2 = new httppost("http://localhost:8080/tao-manager-web/post/xxx");
                list<namevaluepair> nvps = new arraylist<namevaluepair>();  
                nvps.add(new basicnamevaluepair("id", "啊啊啊"));  
                nvps.add(new basicnamevaluepair("name", "secret"));
                urlencodedformentity formentity = new urlencodedformentity(nvps, "gbk");
                request2.setentity(formentity);
                httpresponse response2 = client.execute(request2);
                httpentity entity = response2.getentity();
                objectmapper mapper = new objectmapper();
                user = mapper.readvalue(entity.getcontent(), user.class);
            }else if("delete".equals(param)){

            }else if("put".equals(param)){

            }
        } catch (exception e) {
            e.printstacktrace();
        }
        return user;
    } 
}

4.spring的resttemplate

springmvc.xml增加

<!-- 配置resttemplate -->
    <!--http client factory -->
    <bean id="httpclientfactory"
        class="org.springframework.http.client.simpleclienthttprequestfactory">
        <property name="connecttimeout" value="10000" />
        <property name="readtimeout" value="10000" />
    </bean>

    <!--resttemplate -->
    <bean id="resttemplate" class="org.springframework.web.client.resttemplate">
        <constructor-arg ref="httpclientfactory" />
    </bean>

controller

@controller
public class resttemplateaction {

    @autowired
    private resttemplate template;

    @requestmapping("resttem")
    public @responsebody user resttem(string method) {
        user user = null;
        //查找
        if ("get".equals(method)) {
            user = template.getforobject(
                    "http://localhost:8080/tao-manager-web/get/{id}",
                    user.class, "呜呜呜呜");

            //getforentity与getforobject的区别是可以获取返回值和状态、头等信息
            responseentity<user> re = template.
                    getforentity("http://localhost:8080/tao-manager-web/get/{id}",
                    user.class, "呜呜呜呜");
            system.out.println(re.getstatuscode());
            system.out.println(re.getbody().getusername());

        //新增
        } else if ("post".equals(method)) {
            httpheaders headers = new httpheaders();
            headers.add("x-auth-token", uuid.randomuuid().tostring());
            multivaluemap<string, string> postparameters = new linkedmultivaluemap<string, string>();
            postparameters.add("id", "啊啊啊");
            postparameters.add("name", "部版本");
            httpentity<multivaluemap<string, string>> requestentity = new httpentity<multivaluemap<string, string>>(
                    postparameters, headers);
            user = template.postforobject(
                    "http://localhost:8080/tao-manager-web/post/aaa", requestentity,
                    user.class);
        //删除
        } else if ("delete".equals(method)) {
            template.delete("http://localhost:8080/tao-manager-web/delete/{id}","aaa");
        //修改
        } else if ("put".equals(method)) {
            template.put("http://localhost:8080/tao-manager-web/put/{id}",null,"bbb");
        }
        return user;

    }
}

到此这篇关于java调用restful接口的三种方法的文章就介绍到这了,更多相关java调用restful接口内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!