简体   繁体   中英

Unhandled exception java.net.MalformedURLException in an Android app

I have a problem in my code

void getItembyID(String code){
    String site;
    site = "http:/www.sprii.net/db/getItem.php?pid="+code+"/";
    URL url = new URL(site);
}

I get an exception in the third line while writing in IntelliJ. The problem is with URL url = new URL(site); Should I just try/catch it? Why does it happen? I tried inputting "http://www.google.com/" to see if it works with that and it still gives me the same exception

EDIT: I realised I have an error in my site name. It misses // after http:. However, after changing that I still get "java.net.MalformedURLException"

I realised what the problem was. This error means that the method I'm calling is declared with throws and because of that has to be handled with try{}catch(){} or by adding an identical throws

Make sure String code does not have any spaces, if you should encode it before appending

I got a similar error when I sent the below URL

String unEncodedUrl = " https://yXXXXXXdh.execute-api.us-east-1.amazonaws.com/prod/helloWorld?date=29 Dec 2017";

URL url = new URL(unEncodedUrl);

the above line has thrown error because there are spaces in the date url query value

so you can solve it by encoding the date value

String encodedUrl = " https://yXXXXXXdh.execute-api.us-east-1.amazonaws.com/prod/helloWorld?date= "+URLEncoder.encode(finaldate,"utf-8");

note: do not encode the entire URL only encode the part which contains spaces

You are missing a /

Try using " http://www.sprii.net/db/getItem.php?pid= "

Perhaps you should expand this function so you can see more errors if they occur, like the code below. (By the way, this executes for me, but I don't know any valid "code" value for the argument)

    public void getItembyID(String code) {
    String site;

    site = "http://www.sprii.net/db/getItem.php?pid=" + code + "/";

    try {
        URL url = new URL(site);
    } catch (MalformedURLException e) {
        System.out.println("Error: " + e.getMessage());
        e.printStackTrace();
    }

}

You are missing a / in the url. Should be http://

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM