简体   繁体   English

如何使Spring REST API使用者

[英]how to make spring REST api consumer

I am new to spring``REST api design. 我是spring``REST API设计的spring``REST Somehow I have created a api (producer). 我以某种方式创建了一个api(生产者)。 Now I want to consume this same API . 现在,我想使用相同的API I have never consumed API before. 我以前从未使用过API。 How can I do so ? 我该怎么办? I have tried using HttpURLConnection but couldn't do it. 我尝试使用HttpURLConnection但无法执行。 Below is my code for producer api. 下面是我的生产者api代码。 Now I want to call this API using java code. 现在,我想使用Java代码调用此API。

Rest Api (producer) 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);

        }
    }

postman screenshot 邮递员屏幕截图

在此处输入图片说明

On postman its working fine. 对邮递员来说,它的工作很好。 Now I want to consume this very api programatically. 现在,我想以编程方式使用此api。 how can I do this. 我怎样才能做到这一点。 Basically I need to call this method using some code: 基本上,我需要使用一些代码来调用此方法:

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

don't have much experience in doing so..please guide. 没有太多经验。.请指导。

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

Ok, after much digging in google I made following code but still not able to call rest api. 好的,经过对Google的深入研究,我编写了以下代码,但仍然无法调用rest api。 My code: 我的代码:

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();
    }

}

but still no success. 但仍然没有成功。 Below is the error I get in console: 以下是我在控制台中遇到的错误:

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

Since you are using Spring, you can use RestTemplate which is again a spring library. 由于您正在使用Spring,因此可以使用RestTemplate,它也是一个Spring库。 Please refer rest template 请参考休息模板

This is actually one client, but there are more. 这实际上是一个客户,但还有更多。 Its up to you do decide which one you should use and which suites best to you. 由您决定应使用哪个套件,以及最适合您的套件。

As @Damith said, rest template is a good library, and it's embedded on the springboot dependency tree. 正如@Damith所说,rest模板是一个很好的库,它嵌入在springboot依赖树中。 But also there are some others library, such as OkHttp or JAX-RX which can help you. 但是,还有其他一些库,例如OkHttpJAX-RX可以为您提供帮助。 My favorite one is OkHttp3, Good Luck. 我最喜欢的是OkHttp3,祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM