如何在URL中传递多个参数?

我试图弄清楚如何在URL中传递多个参数。我想将纬度和经度从我的android类传递给Java servlet。我怎样才能做到这一点?

URL url;

double lat=touchedPoint.getLatitudeE6() / 1E6;

double lon=touchedPoint.getLongitudeE6() / 1E6;

url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+lon);

在这种情况下,输出(写入文件)为28.53438677.472097。这是可行的,但我想在两个单独的参数中传递纬度和经度,以便减少在服务器端的工作。如果不可能,我如何至少在lat&之间添加一个空格,lon以便可以使用tokenizerclass获取经度和纬度。我试过以下行,但无济于事。

    url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+" "+lon);

output- Nothing is written to file

url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"&?param2="+lon);

output- 28.534386 (Only Latitude)

url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"?param2="+lon);

output- 28.532577?param2=77.502996

我的servlet代码如下:

req.setCharacterEncoding("UTF-8");

resp.setCharacterEncoding("UTF-8");

final String par1 = req.getParameter("param1");

final String par2 = req.getParameter("param2");

FileWriter fstream = new FileWriter("C:\\Users\\Hitchhiker\\Desktop\\out2.txt");

BufferedWriter out = new BufferedWriter(fstream);

out.write(par1);

out.append(par2);

out.close();

我也想知道这是将数据从android设备传递到服务器的最安全的方法。

回答:

这个

url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"&param2="+lon);

必须工作。出于各种奇怪的原因1,您需要?在第一个参数&之前和之后的参数之前。

使用类似的复合参数

url = new URL("http://10.0.2.2:8080/HelloServlet/PDRS?param1="+lat+"_"+lon);

也可以,但是肯定不是很好。您不能在其中使用空格,因为URL中禁止使用空格,但是您可以将其编码为%20+(但这是更差的样式)。


1声明?将路径和参数&分开以及将参数彼此分开并不能解释任何原因。一些RFC说“在那儿&在那儿使用”,但是我不明白为什么他们没有选择相同的字符。

以上是 如何在URL中传递多个参数? 的全部内容, 来源链接: utcz.com/qa/428661.html

回到顶部