java 代码

java 代码仅供参考如有错误请联系客户,会提供技术支持

java 代码



import java.io.*;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.HashMap;

import java.util.Map;



public class ImageUploadAndQuery {



    // 定义最大查询次数,这里设置为60次,可根据实际情况调整

    private static final int MAX_QUERY_TIMES = 60;

    // 每次查询的间隔时间(单位:毫秒),这里设置为1000毫秒,即1秒,可按需调整

    private static final long QUERY_INTERVAL = 1000;



    public static void main(String[] args) {

        // 图片文件的本地路径,替换为实际要上传的图片路径

        String imagePath = "/path/to/your/image.jpg";

        // 上传图片的服务器接口地址,替换为真实有效的地址

        String uploadUrl = "http://aa.fatiegongju.com/api/upload";

        // 模拟多个请求参数,可根据实际情况替换具体值

        Map parameters = new HashMap<>();

        parameters.put("dati_type", "8091"); //答题类型

        parameters.put("acc_str", "xxxxxxxxxxxx");//用户自己的答题串 以便计费 登录账号查询自己的答题密码串

        parameters.put("extra_str", "题目是。。。。"); //描述问题内容,以便答题人员能够理解答题

        parameters.put("zz", ""); //作者帐号(给予返利)

        parameters.put("pri", "9"); //优先级

        parameters.put("timeout", "70"); //答题时间不要太小,否则容易超时而不能返回结果 

    

        try {

            String imageIndex = uploadImageWithParams(imagePath, uploadUrl, parameters);

            if (imageIndex!= null  && imageIndex.length()>0 && !imageIndex.startsWith("#")) {

                queryImageInfo(imageIndex);

            } else {

                System.err.println("图片上传出错,错误信息: " + imageIndex);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }



    public static String uploadImageWithParams(String imagePath, String uploadUrl, Map parameters) throws IOException {

        File imageFile = new File(imagePath);

        URL url = new URL(uploadUrl);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");

        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");

        connection.setDoOutput(true);



        // 构建请求体

        String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";

        StringBuilder requestBodyBuilder = new StringBuilder();



        // 添加参数部分到请求体

        for (Map.Entry entry : parameters.entry()) {

            requestBodyBuilder.append("--").append(boundary).append("\r\n");

            requestBodyBuilder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"\r\n\r\n");

            requestBodyBuilder.append(entry.getValue()).append("\r\n");

        }



        // 添加图片文件部分到请求体

        requestBodyBuilder.append("--").append(boundary).append("\r\n");

        requestBodyBuilder.append("Content-Disposition: form-data; name=\"pic\"; filename=\"").append(imageFile.getName()).append("\"\r\n");

        requestBodyBuilder.append("Content-Type: image/jpeg\r\n\r\n");



        // 将请求体字符串转换为字节数组

        byte[] requestBodyPrefix = requestBodyBuilder.toString().getBytes("UTF-8");



        // 获取输出流,先写入参数和图片头部相关字节

        try (OutputStream outputStream = connection.getOutputStream()) {

            outputStream.write(requestBodyPrefix);



            // 再写入图片文件内容

            try (FileInputStream fileInputStream = new FileInputStream(imageFile)) {

                byte[] buffer = new byte[1024];

                int bytesRead;

                while ((bytesRead = fileInputStream.read(buffer))!= -1) {

                    outputStream.write(buffer, 0, bytesRead);

                }

            }



            // 写入结束边界字节

            byte[] endBoundary = ("\r\n--" + boundary + "--\r\n").getBytes("UTF-8");

            outputStream.write(endBoundary);

        }



        // 获取服务器响应

        int responseCode = connection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {

                StringBuilder response = new StringBuilder();

                String line;

                while ((line = reader.readLine())!= null) {

                    response.append(line);

                }

                return response.toString();

            }

        } else {

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {

                StringBuilder errorResponse = new StringBuilder();

                String line;

                while ((line = reader.readLine())!= null) {

                    errorResponse.append(line);

                }

                return "#" + errorResponse.toString();

            }

        }

    }



    public static void queryImageInfo(String imageIndex) throws IOException { 

	

        String queryUrl = "http://aa.fatiegongju.com/api/result?id=" + imageIndex;

        URL url = new URL(queryUrl);

        int queryTimes = 0;

        while (queryTimes < MAX_QUERY_TIMES) {

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");



            // 获取服务器响应

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {

                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {

                    StringBuilder response = new StringBuilder();

                    String line;

                    while ((line = reader.readLine())!= null) {

                        response.append(line);

                    }

                    String result = response.toString().trim();

                    if (result.isEmpty()) {

                        System.out.println("服务器仍在处理图片,请稍候...");

                    } else if (result.startsWith("#")) {

                        System.err.println("图片处理出错,错误信息: " + result);

						return result;

                        break;

                    } else {

                        System.out.println("图片处理成功,信息: " + result);

							return result;

                        break;

                    }

                }

            } else {

                System.err.println("查询图片信息时请求出错,状态码: " + responseCode);

                break;

            }

            queryTimes++;

            // 等待一段时间后再次查询

            try {

                Thread.sleep(QUERY_INTERVAL);

            } catch (InterruptedException e) {

                Thread.currentThread().interrupt();

                System.err.println("查询等待过程被中断");

                break;

            }

        }

        if (queryTimes == MAX_QUERY_TIMES) {

            System.err.println("已达到最大查询次数,仍未获取到有效图片处理信息");

        }

		return "#已达到最大查询次数";

    }

}

说明:xxxxxxxxxxxxxxx替换成密码串 提交成功后会返回一组字符串 直接用这个字符串每1秒循环get提交到http://aa.fatiegongju.com/api/result 即可 一直取到答案为止 取到答案判断 一下答案的第一个字符串 如果为“#” 即为报错了 如果不是#开头 即为返回的答案