如何使Spring REST API使用者

时间:2018-09-26 11:19:59

标签: java spring rest spring-boot

我是spring``REST api设计的新手。我以某种方式创建了一个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);

        }
    }

邮递员屏幕截图

enter image description here

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

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

没有太多经验。.请指导。

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

好吧,在Google进行了很多挖掘之后,我编写了以下代码,但仍然无法调用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

2 个答案:

答案 0 :(得分:0)

由于您使用的是Spring,因此可以使用RestTemplate,它也是一个Spring库。 请参阅rest template

这实际上是一个客户,但还有更多。由您决定应使用哪个套件,以及最适合您的套件。

答案 1 :(得分:0)

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