获取错误 java.lang.IllegalArgumentException:意外 url

Getting Error java.lang.IllegalArgumentException: unexpected url

您好,我正在尝试使用 json 解析向服务器发送一些数据,但是 activity 崩溃并导致
java.lang.IllegalArgumentException: 意外 url

这是我的 Activity 代码,我正在评论出现错误的行。

public class LoginActivity extends AppCompatActivity { **// Showing Error at this LIne**

public Location location;
private Button btnLogin;
private boolean doubleBackToExitPressedOnce = false;
private EditText phoneNo, password;
private CheckBox cbShow, cbRemember;
private NetworkUtil networkUtil;
private SharePrefUtil sharePref;
private LocationInfo locationInfo;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    networkUtil = new NetworkUtil(getApplicationContext());
    sharePref = new SharePrefUtil(getApplicationContext());
    initScreen();

    if (sharePref.getValueFromSharePref("remeberFlag").equalsIgnoreCase("true")) {
        phoneNo.setText(sharePref.getValueFromSharePref("mobileno"));
        password.setText(sharePref.getValueFromSharePref("password"));
        cbRemember.setChecked(true);
    }
}



private void initScreen() {
    LocationLibrary.showDebugOutput(true);
    try {
        LocationLibrary.initialiseLibrary(LoginActivity.this, 60 * 1000, 60 * 1000 * 2, "com.aspeage.jagteraho");

    } catch (UnsupportedOperationException e) {
        Toast.makeText(this, "Device doesn't have any location providers", Toast.LENGTH_LONG).show();
    }

    phoneNo = (EditText) findViewById(R.id.ed_phoneno);
    password = (EditText) findViewById(R.id.ed_password);
    cbRemember = (CheckBox) findViewById(R.id.cbox_rememberme);
    cbRemember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) sharePref.setValueInSharePref("remeberFlag", "true");
            else sharePref.setValueInSharePref("remeberFlag", "false");
        }
    });

    cbShow = (CheckBox) findViewById(R.id.cbox_showpass);
    cbShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                password.setInputType(129);
            }
        }
    });
    btnLogin = (Button) findViewById(R.id.btn_login);
    btnLogin.setOnClickListener(new ButtonClick());
}

private class ButtonClick implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                btnLoginClicked();
                break;
            default:
                break;
        }
    }
}

private void btnLoginClicked() {
    if(phoneNo.getText().toString().trim().equals("admin") && password.getText().toString().trim().equals("admin")) {
        loginService();
    }
    if (validation()) {
        if (cbRemember.isChecked())
            rememberMe(password.getText().toString().trim());
        if (networkUtil.isConnected()) {
            loginService();
        } else {
            new SweetAlertDialog(LoginActivity.this, cn.pedant.SweetAlert.SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("Oops...")
                    .setContentText("No Network Connection")
                    .show();
        }
    }
}

/**
 * save username and password in SharedPreferences.
 *
 * @param //password is key value for storing in SharedPreferences.
 */
public void rememberMe(String password) {
    SharePrefUtil sharePref = new SharePrefUtil(getApplicationContext());
    sharePref.setValueInSharePref("password", password);
}

private boolean validation() {
    int errorCount = 0;
    if (phoneNo.getText().toString().trim().equals("")
            || phoneNo.getText().length() != 10) {
        phoneNo.setError("Enter valid phone number");
        errorCount = errorCount + 1;
        if (errorCount == 1) {
            phoneNo.requestFocus();
        }
    } else {
        phoneNo.setError(null);
    }
    if (password.getText().toString().trim().equals("")
            || password.getText().length() != 12) {
        password.setError("Enter valid password");
        errorCount = errorCount + 1;
        if (errorCount == 1) {
            password.requestFocus();
        }
    } else {
        password.setError(null);
    }
    if (errorCount == 0) {
        return true;
    } else {
        return false;
    }

}

private void batteryTimer(){
    Timer timer = new Timer();
    TimerTask hourlyTask = new TimerTask() {
        @Override
        public void run() {
            if (networkUtil.isConnected()) {
                batteryLevelCheckService(); // **Getting Error at this Line**
            }
            else {
                offlineBatteryStatus();
            }
        }
    };
    timer.scheduleAtFixedRate(hourlyTask, 01, 60000);
}

private void batteryLevelCheckService() {
    OkHttpClient client = new OkHttpClient();
    String requestURL = String.format(getResources().getString(R.string.service_batteryLevelCheckService));

    JSONArray jsonArrayRequest = new JSONArray();
    JSONObject jsonRequest;
    try {
        List<BatteryStatusModel> batStatusOffline = new Select().from(BatteryStatusModel.class).execute();
        if (batStatusOffline.size() > 0) {
            for (BatteryStatusModel batStatusObject : batStatusOffline) {
                jsonRequest = new JSONObject();
                jsonRequest.accumulate("strTime", batStatusObject.batStatTime);
                jsonRequest.accumulate("batteryStatusLat", "" + batStatusObject.battery_lat);
                jsonRequest.accumulate("batteryStatusLog", "" + batStatusObject.battery_lon);
                jsonRequest.accumulate("empAuthKey", sharePref.getValueFromSharePref("authKey"));
                jsonRequest.accumulate("mobno", "" + sharePref.getValueFromSharePref("mobileno"));
                jsonRequest.accumulate("strBatteryStatus", "" + batStatusObject.batteryStatus);
                jsonArrayRequest.put(jsonRequest);
            }
        }

        Intent intent = this.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
        int percent = (level * 100) / scale;

        Date today = Calendar.getInstance().getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String time = simpleDateFormat.format(today);

        jsonRequest = new JSONObject();
        jsonRequest.accumulate("strTime", time);
        jsonRequest.accumulate("batteryStatusLat", "" + locationInfo.lastLat);
        jsonRequest.accumulate("batteryStatusLon", "" + locationInfo.lastLong);
        jsonRequest.accumulate("empAuthKey", sharePref.getValueFromSharePref("authKey"));
        jsonRequest.accumulate("mobNo", "" + sharePref.getValueFromSharePref("mobileno"));
        jsonRequest.accumulate("strBatteryStatus", "" + percent);
        jsonArrayRequest.put(jsonRequest);
    } catch (Exception e) {
        e.printStackTrace();
    }

    RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonArrayRequest.toString());
    Request request = new Request.Builder()
            .url(requestURL) // Getting Error at this Line
            .post(body).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseString = response.body().string();
                try {
                    JSONObject jsonResponse = new JSONObject(responseString);
                    String status = jsonResponse.getString("status");
                    String message = jsonResponse.getString("message");
                    Log.d("jagteraho", "response :: status: " + status.toString() + " message: " + message);
                    if (status.equals("success")) {
                        new Delete().from(BatteryStatusModel.class).execute();
                    } else if (status.equals("failure")) {
                    } else if (status.equals("error")) {
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

这是我的Logcat

java.lang.IllegalArgumentException: unexpected url: >http://192.168.2.20:8080/jagteraho/batteryStatus/save
at okhttp3.Request$Builder.url(Request.java:143)
at com.aspeage.jagteraho.LoginActivity.batteryLevelCheckService(LoginActivity.java:270)
at com.aspeage.jagteraho.LoginActivity.access0(LoginActivity.java:59)
at com.aspeage.jagteraho.LoginActivity.run(LoginActivity.java:216)
at java.util.Timer$TimerImpl.run(Timer.java:284) 

请帮助我提供可能的解决方案,我在 Android 开发方面还很陌生

您的错误来自 OkHttp。

如果您搜索错误消息,您可以看到 OkHttp 在哪里生成错误消息:

https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/Request.java#L142

  HttpUrl parsed = HttpUrl.parse(url);
  if (parsed == null) throw new IllegalArgumentException("unexpected url: " + url);
  return url(parsed);

表示您的URL无效。正如对您问题的评论所指出的:>http://192.168.2.20:8080/jagteraho/batteryStatus/save 不是有效的 URL.

您需要删除 >