为什么我在 HttpUrlConnection Java 中使用 httpStatus:401 或 httpStatus 500?

问题描述

我尝试使用 HttpURLConnection 发布请求

这是请求正文:

enter image description here

这是请求头:

enter image description here

这是我的代码:

public static String postSms(long mNo,long cepNo,String mesaj){
        
        
        String responseLine = null;
        String url = getSmsUrl();
        String authKey = getSmsAuthKey();
        
                try {
            
            URL s_url = new URL(url);
            httpCon = (HttpURLConnection) s_url.openConnection();           
            if(authKey != null){
                httpCon.setRequestProperty("yd-x-token",authKey);  
            }
            httpCon.setRequestMethod("POST");
            httpCon.setRequestProperty("Content-Type","application/json; utf-8");
            httpCon.setRequestProperty("Accept","application/json");
            httpCon.setDoOutput(true);
            int responseCode = httpCon.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                JSONObject msj = new JSONObject();          
                msj.put("toNumber",cepNo);
                msj.put("smsText",mesaj);
                
                try(OutputStream os = httpCon.getOutputStream()) {
                    byte[] input = msj.toString().getBytes("utf-8");
                    os.write(input,input.length);           
                }           
                try(BufferedReader br = new BufferedReader(
                          new InputStreamReader(httpCon.getInputStream(),"utf-8"))) {
                            StringBuilder response = new StringBuilder();
                             responseLine = null;
                            while ((responseLine = br.readLine()) != null) {
                                response.append(responseLine.trim());
                            }
                        }
            }else return "ER|[sendNotification][Sms] <===> "+responseCode;            
        } catch (MalformedURLException e) {
            log.error("ER|[sendNotification][Sms] <===> Hata "+e);
            return "ER|[sendNotification][Sms] <===> Hata "+e;
        } catch (IOException e) {
            log.error("ER|[sendNotification][Sms] <===> Hata "+e);
            return "ER|[sendNotification][Sms] <===> Hata "+e;
        }catch (JSONException e){

       }
         return "OK";

        }

当我像两张照片一样尝试邮递员时,它成功了。但是当我尝试使用 HttpURLConnection 时,响应代码 = 500。有时 responseCode 会出现 401,但是当他们提供随 httpstatus 500 更改的新令牌时。为什么我会收到此错误。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)