首页 > 解决方案 > 如何使spring REST api消费者

问题描述

我是spring``RESTapi 设计的新手。不知何故,我创建了一个 api(生产者)。现在我想吃同样API的。我以前从未使用过 API。我该怎么做?我试过使用HttpURLConnection但做不到。下面是我的生产者 api 代码。现在我想使用 java 代码调用这个 API。

Rest Api(生产者)

@PostMapping(value="register")
    public ResponseEntity<CoreResponseHandler> doRegister(@RequestPart String json,@RequestParam(required=false) MultipartFile file)  throws JsonParseException, JsonMappingException, IOException {    
        try {

            String imgPath = env.getProperty("image_path");

            String outputDir = imgPath; 

            RegEntity reg = new ObjectMapper().readValue(json, RegEntity.class);

            String  result = validateInsertRegBean(reg);
            if(!result.equalsIgnoreCase("success")) {
                return new ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.BAD_REQUEST, ResponseStatusEnum.FAILED, ApplicationResponse.Failed,result),HttpStatus.BAD_REQUEST);

            }
            String imagePath=null;
            System.out.println("=================================");
            if(file!=null && !file.isEmpty()) {
                System.out.println("file NOT nOT NOT EmpTY");
            String username=reg.getUsername();
            File userFile = new File(outputDir+username);
            if(!userFile.exists()) {
                userFile.mkdir();
            }

            try {
                file.transferTo(new File(outputDir+username+File.separator+ file.getOriginalFilename()));
                System.out.println("***************   "+file.getOriginalFilename());
            } catch (IOException e) {
                return new ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.BAD_REQUEST, ResponseStatusEnum.FAILED, ApplicationResponse.Failed,"image unable to upload"),HttpStatus.BAD_REQUEST);
            }


            File ff[] = userFile.listFiles();
            for(File f:ff) {
                if(f.getName().contains("thumbnail"))
                    f.delete();
            }


            Thumbnails.of(new File(outputDir+username+File.separator).listFiles())
            .size(100, 100)
            .outputFormat("jpg")
            .toFiles(Rename.SUFFIX_HYPHEN_THUMBNAIL);

            imagePath=outputDir+username+File.separator+file.getOriginalFilename();

            }
            Date dt = new Date();
            long lngDt = dt.getTime();
            Ofuser ofuser = new Ofuser();
            ofuser.setBlockedNum(null);
            ofuser.setEmail(reg.getEmail());
            ofuser.setEncryptedPassword(reg.getEncryptedPassword());
            ofuser.setName(reg.getName());
            ofuser.setStatus(reg.getStatus());
            ofuser.setUsername(reg.getUsername());
            ofuser.setVcardResize(null);
            ofuser.setImage(null);
            ofuser.setPlainPassword(null);
            ofuser.setCreationDate(lngDt+"");
            ofuser.setModificationDate(lngDt+"");
            ofuser.setImagePath(imagePath);
            Ofuser tempuser = ofuserService.save(ofuser);
            IdMaster idMaster0 = new IdMaster();
            idMaster0.setUsername(tempuser.getUsername());
            idMaster0.setUserId(lngDt+"");
            IdMaster tempidMaster = idMasterService.save(idMaster0);
            if(tempuser!=null && tempidMaster!=null) {
                System.out.println("################## "+tempuser.getUsername());
                return new ResponseEntity<CoreResponseHandler>(
                        new SuccessResponseBean(HttpStatus.OK, ResponseStatusEnum.SUCCESSFUL, ApplicationResponse.SUCCESSFUL),
                        HttpStatus.OK);
            }
            else {
                return new ResponseEntity<CoreResponseHandler>(
                        new SuccessResponseBean(HttpStatus.BAD_REQUEST, ResponseStatusEnum.FAILED, ApplicationResponse.Failed),
                        HttpStatus.BAD_REQUEST);
            }

        }catch(Exception ex) {
            ex.printStackTrace();
            return new ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.BAD_REQUEST, ResponseStatusEnum.FAILED, ApplicationResponse.Failed,"something went wrong!!"),HttpStatus.BAD_REQUEST);

        }
    }

邮递员截图

在此处输入图像描述

在邮递员上工作正常。现在我想以编程方式使用这个非常 API。我怎样才能做到这一点。基本上我需要使用一些代码来调用这个方法:

 @PostMapping(value="register")
        public ResponseEntity<CoreResponseHandler> doRegister(@RequestPart String json,@RequestParam(required=false) MultipartFile file){}

没有太多这样做的经验..请指导。

==================================================== ===========================

好的,在谷歌大量挖掘之后,我制作了以下代码,但仍然无法调用 rest api。我的代码:

package com.google.reg.utils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:8012/register");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW charset=utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            JSONObject jsonObject = buidJsonObject();
            setPostRequestContent(conn, jsonObject);
            conn.connect();
            System.out.println(conn.getResponseCode());
            if(conn.getResponseCode()==200){
                BufferedReader reader= new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    stringBuilder.append(line + "\n");
                }
                System.out.println(stringBuilder+" <<<<<<<<<<<<<<<<<<<<<<<<<" );
                jsonObject=new JSONObject(stringBuilder.toString());    
            }
            else{
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    stringBuilder.append(line + "\n");
                }
                System.out.println(stringBuilder+" <<<<<<<<<<<<<<<<<<<<<<<<<" );
                System.out.println("ERRORERRORERRORERRORERRORERRORERRORERRORERROR"+conn.getResponseCode());
            }

        }catch(Exception ex) {
            ex.printStackTrace();
        }

    }

    private static  JSONObject buidJsonObject() throws JSONException {

        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("username", "129898912");
        jsonObject.accumulate("encryptedPassword", "encpass");
        jsonObject.accumulate("name",  "fish");
        jsonObject.accumulate("email",  "fish@fish.com");
        jsonObject.accumulate("status",  "active");


        return jsonObject;
    }

    private static void setPostRequestContent(HttpURLConnection conn, 
            JSONObject jsonObject) throws IOException {

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(jsonObject.toString());
        writer.flush();
        writer.close();
        os.close();
    }

}

但仍然没有成功。以下是我在控制台中遇到的错误:

400
<html><body><h1>Whitelabel Error Page</h1><p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p><div id='created'>Wed Sep 26 12:28:17 UTC 2018</div><div>There was an unexpected error (type=Bad Request, status=400).</div><div>Required request part &#39;json&#39; is not present</div></body></html>
 <<<<<<<<<<<<<<<<<<<<<<<<<
ERRORERRORERRORERRORERRORERRORERRORERRORERROR400

标签: javaspringrestspring-boot

解决方案


正如@Damith 所说,rest 模板是一个很好的库,它嵌入在 springboot 依赖树中。但也有一些其他的库,比如OkHttpJAX-RX可以帮助你。我最喜欢的是 OkHttp3,祝你好运。


推荐阅读