Don't you know how to use Java code to send post requests and get requests?

Usually when you are studying and working, you will encounter an interface for you to obtain the corresponding data, which also includes post requests and get requests. The corresponding tools are provided below.

1. Java code implements sending get request

public static String getpage(String tempurl,String bm,String token ) {
        String result="";
        try {
            URL url = new URL(tempurl);
            InputStream is = null;
            URLConnection con=url.openConnection();
            con.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            con.setConnectTimeout(120000);
            con.setReadTimeout(120000);
            con.addRequestProperty("x-access-token",token);
            con.connect();
            try {
                is = con.getInputStream();
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(is,bm));
                    String s="";
                    String linesep = System.getProperty("line.separator");
                    while((s = reader.readLine())!=null){
                        result += s+linesep ;
                    }
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (Exception e1) {
                        }
                    }
                }
                is.close();
            }catch (FileNotFoundException e2) {
                ;
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return result;
    }

Two, Java code to send post request

   private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

   
   public static String sendPost(JSONObject json, String URL,String token) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        post.setHeader("Content-Type", "application/json");
        post.setHeader("Authorization", "Basic YWRtaW46");
        post.setHeader("x-access-token",token);
        String result;
        try {
            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(s);
            // 发送请求
            HttpResponse httpResponse = client.execute(post);
            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();
            result = strber.toString();
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("请求服务器成功,做相应处理");
            } else {
                System.out.println("请求服务端失败");
            }
        } catch (Exception e) {
            logger.error("请求异常:"+e.getMessage());
            throw new RuntimeException(e);
        }
        return result;
    }

Pay attention during use: all kinds of parameters are set correctly

Guess you like

Origin blog.csdn.net/lf21qp/article/details/131244175