URLEncoder encode / URLDecoder decode in java (Android)

2022-09-03 06:10:38

我想在应用程序中使用URLEncoder/URLDecoder类(java.net.URLEncoder/URLDecoder)和方法:encode(String s,String enc)/decode(String s,String enc),但我不知道什么是String参数enc的值?我想在“x-www-form-urlencoded”MIME内容类型中编码/解码。感谢您的帮助。


答案 1

编码参数是您正在使用的字符编码。.For example "UTF-8"


答案 2

首先,您需要将内容类型设置为“x-www-form-urlencoded”。然后,无论您要编码什么内容,请使用“UTF-8”对其进行编码。

例如:

要将内容设置为“x-www-form-urlencoded”:

URL url = new URL("http://www.xyz.com/SomeContext/SomeAction"); <br>
URLConnection urlConnection = url.openConnection();<br>
....<br>
....<br>
urlConnection.setRequestProperty("Content-type","application/x-www-form-urlencoded");


或者,如果您使用的是某些JSP,则可以在其上编写以下内容。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %><br>
< META http-equiv="Content-Type" content="text/html; charset=UTF-8">


< FORM action="someaction.jsp" enctype="application/x-www-form-urlencoded" name="InputForm" method="POST">

要使用 URLEncoder:

String encodedString = URLEncoder.encode("hello","UTF-8");

推荐