[英]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. 在用IntelliJ编写时,第三行出现异常。 The problem is with
URL url = new URL(site);
问题出在
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 我尝试输入
"http://www.google.com/"
以查看其是否适用,但仍然给我同样的例外
EDIT: I realised I have an error in my site name. 编辑:我意识到我在我的网站名称中有一个错误。 It misses // after http:.
它在http:之后遗漏//。 However, after changing that I still get "java.net.MalformedURLException"
但是,更改后,我仍然得到“ 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
此错误意味着我正在调用的方法是使用
throws
声明的,因此必须使用try{}catch(){}
或通过添加相同的throws
Make sure String code
does not have any spaces, if you should encode it before appending 如果您应该在附加之前对它进行编码,请确保
String code
没有任何空格
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";
字符串unEncodedUrl =“ https://yXXXXXXdh.execute-api.us-east-1.amazonaws.com/prod/helloWorld?date=2017年 12月29日”;
URL url = new URL(unEncodedUrl);
URL url =新URL(unEncodedUrl);
the above line has thrown error because there are spaces in the date url query value 上一行已引发错误,因为日期url查询值中有空格
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");
字符串encodeUrl =“ 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 注意:请勿对整个URL进行编码,而仅对包含空格的部分进行编码
You are missing a / 您缺少/
Try using " http://www.sprii.net/db/getItem.php?pid= " 尝试使用“ 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://
应该是http://
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.