谁能告诉我错在哪里并加以改正?

我错误的原因是想把原来的for循环用于现在的API中,但是原来的API只有一个apikey并且是get请求,而现在的API有apikey和secretkey并且是POST请求

img

img


package chazhao;
import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import java.io.*;
import java.net.*;
public class chazhao {
    public static void main(String[] args) throws IOException  {
        FileWriter fileWriter = new FileWriter("手机号码.txt");
        String httpUrl = "http://gsd.api.bdymkt.com/sms";
        String httpArg = "";
        for (int i = 0; i < 9999; i++) {
            if (i >= 1000) {
                httpArg = "phone=135" + String.valueOf(i) + "0015";
            } else if (i >= 100) {
                httpArg = "phone=1350" + String.valueOf(i) + "0015";
            } else if (i >= 10) {
                httpArg = "phone=13500" + String.valueOf(i) + "0015";
            } else {
                httpArg = "phone=135000" + String.valueOf(i) + "0015";
            }
            String jsonResult = request(httpUrl, httpArg);
            if (jsonResult.contains("上海")) {
                fileWriter.write(httpArg + "\n\t");
            }
        }
        fileWriter.flush();
        fileWriter.close();
    }

    /**
     * @param urlAll  :请求接口
     * @param httpArg :参数
     * @return 返回结果
     */
    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sb = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();//打开url连接
            connection.setConnectTimeout(15000);//设置连接超时时间
            connection.setReadTimeout(15000);//设置读取超时时间
            connection.setRequestMethod("POST");//设置请求参数,即具体的http方法
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey", " *************");
            connection.setDoOutput(true);//设置是否向httpUrlConnection输出;对于post请求,参数要放在http正问内,因此需要设置为true(默认情况下是false)
            connection.setDoInput(true);//设置是否从httpUrlConnection读入,默认情况下是true
            connection.connect();//调用connect连接远程资源
            InputStream is = connection.getInputStream();//利用getInputStream()访问资源数据
            BufferedReader reader1 = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader1.readLine()) != null) {
                sb.append(strRead);
                sb.append("\r\n");
            }
            reader.close();
            result = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}


下面是API示例代码


import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;

// 号码归属查询api Java示例代码
public class RequestDemo {
    public static void main(String[] args) {
        String path = "http://gsd.api.bdymkt.com/sms";
        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);
        request.setCredentials("您的 access key", "您的 secret key");

        request.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");
        
        request.addQueryParameter("mobile", "");
        
        String requestExample = "\r\nimport com.baidubce.http.ApiExplorerClient;\r\nimport com.baidubce.http.AppSigner;\r\nimport com.baidubce.http.HttpMethodName;\r\nimport com.baidubce.model.ApiExplorerRequest;\r\nimport com.baidubce.model.ApiExplorerResponse;\r\n\r\n\/\/ 号码归属查询api Java示例代码\r\npublic class RequestDemo {\r\n    public static void main(String[] args) {\r\n        String path = \"http:\/\/gsd.api.bdymkt.comhttp:\/\/gwgp-g8eennmvmcz.n.bdcloudapi.com\/sms\";\r\n        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);\r\n        request.setCredentials(\"您的 access key\", \"您的 secret key\");\r\n\r\n        request.addHeaderParameter(\"Content-Type\", \"application\/json;charset=UTF-8\");\r\n        \r\n        request.addQueryParameter(\"mobile\", \"\");\r\n        \r\n        \r\n\r\n        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());\r\n\r\n        try {\r\n          ApiExplorerResponse response = client.sendRequest(request);\r\n          \/\/ 返回结果格式为Json字符串\r\n          System.out.println(response.getResult());\r\n        } catch (Exception e) {\r\n          e.printStackTrace();\r\n        }\r\n    }\r\n}";
        request.setJsonBody(requestExample);
        

        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());

        try {
          ApiExplorerResponse response = client.sendRequest(request);
          // 返回结果格式为Json字符串
          System.out.println(response.getResult());
        } catch (Exception e) {
          e.printStackTrace();
        }
    }
}

那个sms的http接口写错了吧,request异常,返回的result为null,所以调contains方法的时候报NPE


public class chazhao {
    public static void main(String[] args) throws IOException {
        FileWriter fileWriter = new FileWriter("手机号码.txt");
        String httpUrl = "http://gsd.api.bdymkt.com/sms";
        String httpArg = "";
        for (int i = 0; i < 9999; i++) {
            if (i >= 1000) {
                httpArg = "phone=135" + String.valueOf(i) + "0015";
            } else if (i >= 100) {
                httpArg = "phone=1350" + String.valueOf(i) + "0015";
            } else if (i >= 10) {
                httpArg = "phone=13500" + String.valueOf(i) + "0015";
            } else {
                httpArg = "phone=135000" + String.valueOf(i) + "0015";
            }
            String jsonResult = request(httpUrl, httpArg);
            if (jsonResult.contains("上海")) {
                fileWriter.write(httpArg + "\n\t");
            }
        }
        fileWriter.flush();
        fileWriter.close();
    }

    /**
     * @param urlAll  :请求接口
     * @param httpArg :参数
     * @return 返回结果
     */
    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
                                          
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey", " ************");
            connection.setDoOutput(true);
            connection.getOutputStream().write(httpArg.getBytes());
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
package chazhao;

import java.io.*;
import java.net.*;

public class Chazhao {
    public static void main(String[] args) throws IOException {
        FileWriter fileWriter = new FileWriter("手机号码.txt", "UTF-8");
        String httpUrl = "http://gsd.api.bdymkt.com/sms";
        String httpArg = "";
        for (int i = 0; i < 10000; i++) {
            String phoneNum = String.format("135%04d15", i);
            String jsonResult = request(httpUrl, "phone=" + phoneNum);
            if (jsonResult.contains("上海")) {
                fileWriter.write(phoneNum + "\n");
            }
        }
        fileWriter.flush();
        fileWriter.close();
    }

    /**
     * @param httpUrl :请求接口
     * @param httpArg :参数
     * @return 返回结果
     */
    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sb = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(15000);
            connection.setReadtimeout(15000);
            connection.setRequestMethod("POST");
            // Replace "*************" with your actual API key
            connection.setRequestProperty("apikey", "*************");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();
            InputStream is = connection.getInputStream();
            BufferedReader reader1 = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader1.readLine()) != null) {
                sb.append(strRead);
                sb.append("\r\n");
            }
            reader1.close(); // Use reader1 instead of reader
            result = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

  • 你可以参考下这个问题的回答, 看看是否对你有帮助, 链接: https://ask.csdn.net/questions/7561713
  • 这篇博客你也可以参考下:我在哪?从何处来,又到哪里去?
  • 除此之外, 这篇博客: 怎么计算一个图像的面积呢?????中的 任务描述 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 本关任务:设计一个矩形类、一个圆形类和一个图形基类,计算并输出相应图形面积。

  • 您还可以看一下 刘建行老师的非计算机专业,转行程序员?我可以帮你课程中的 引言小节, 巩固相关知识点
  • 以下回答由chatgpt基于相关博客总结生成:

    方法一: 调试工具 使用合适的调试工具可以帮助你找出代码中的错误。例如,在Python中可以使用pdb库来进行交互式的调试,可以查看变量值,单步执行代码等。另外,也可以使用IDE内置的调试功能,例如PyCharm的调试器可以快速定位代码中的问题。

    方法二: 打印日志 在代码中添加适当的打印语句,输出关键变量的值,以及程序执行的位置等信息,可以帮助你更好地理解代码的实际运行情况。同时,打印的日志可以保存下来,供以后进一步分析使用。

    方法三: 请教他人 寻求其他人的帮助也是解决问题的有效方法。可以在相关的技术社区或论坛上提问,描述自己的问题以及已经采取的步骤,并给出尽可能多的代码信息。也可以联系自己所在的团队中的开发人员来共同探讨问题的解决方法。

    方法四: 阅读文档和参考资料 往往在开发中遇到的问题或错误,可以在相关的文档和参考资料中寻找答案。这里的资料不仅包括官方文档,还包括社区中的常见问题解答和经验分享等。因此,充分利用文档和参考资料,可以帮助你更快地解决问题。

    方法五: 思考和分析 最后,也是最重要的是要保持头脑清醒,分析自己遇到的问题和错误,思考出具体的解决方案。需要学会排除干扰因素,重点关注问题的细节,逐步分析和排查原因。如果遇到未知问题,可以尝试使用搜索引擎这一工具快速找到相关的答案和解决办法。

第一个找不到文件异常:“手机号码.txt”文件找不到,请检查路径是否正确;也有可能是你的InputStream为空造成的。
第二个空指针:由于的request()方法为返回空值造成的,可以把request()方法中的“String result = null”改为“String result =new String()”,初始化一个值。