Request获取请求编码

  • 2、请求编码
  • *客户端发送给服务器的请求参数是什么编码:
  • 客户端首先要打开一个页面,然后在页面中提交表单或点击超链接,在请求这个页面时,服务器响应的编码是什么,那么客服端发送请求时就是什么
  • *服务器端默认使用什么编码来解码参数:
  • 服务器端默认使用ISO-8859-1来解码,所以这一定会出现乱码,因为iso不支持中文。
  • *请求编码处理分为两种:GET和POST,GET请求参数不在请求体中,而POST请求参数在请求体中,所以它们的处理方式是不同的。
  • *GET请求编码处理:
  • 》String username = new String(request.getParmeter(“iso-8859-1”),“utf-8”);
  • 》在servlet.xml中配置URIEncoding(“utf-8”);
  • *POST请求编码处理
  • 》String username = new String(request.getParameter(“iso-8859-1”),“utf-8”);
  • 》在获取参数之前调用request.setCharacterEncoding(“utf-8”);

public class AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**

  • 1、先获取来使用iso的错误字符串
  • 2、回退,使用utf-8重编
    /
    String name = request.getParameter(“username”);
    byte[] b = name.getBytes(“iso-8859-1”);
    name = new String(b,“utf-8”);
    System.out.println(name);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    /
    *
  • 1、在获取参数之前,需要先调用request.setCharacterEncoding(“utf-8”);
  • 2、使用getParameter()来获取参数
    */
    request.setCharacterEncoding(“utf-8”);
    String username = request.getParameter(“username”);
    System.out.println(username);
    }
    }
### 如何在HTTP请求中设置参数 对于不同的HTTP方法,设置参数的方式有所不同。 #### HTTP GET 请求中的参数设置 在HTTP GET请求中,参数通过URL的查询字符串形式附加到请求地址后面。这些参数以键值对的形式存在,并由问号`?`分隔开,多个参数之间则用&连接[^1]: 例如访问如下链接: ``` http://example.com/page?parameter=value&also=another ``` 这里`parameter=value` 和 `also=another` 就是GET请求所携带的两个参数。 #### HTTP POST 请求中的参数设置 而在HTTP POST请求里,参数通常放在消息体(body)内传送。具体实现取决于使用的编程语言和技术栈,在Java环境中可以借助Apache HttpClient库来构建POST请求并附带参数数据[^2]: 下面是一个简单的例子展示怎样利用此库创建带有表单编码类型的POST请求: ```java // 导入必要的类 import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class PostExample { public static void main(String[] args) throws Exception { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { // 创建HttpPost对象指定目标网址 HttpPost postRequest = new HttpPost("https://www.example.com/api"); // 设置实体内容为application/x-www-form-urlencoded格式 String paramData = "param1=value1&param2=value2"; StringEntity entity = new StringEntity(paramData); entity.setContentType("application/x-www-form-urlencoded"); postRequest.setEntity(entity); // 执行请求获取响应 HttpResponse response = httpClient.execute(postRequest); System.out.println(response.getStatusLine().getStatusCode()); } } } ``` 这段代码展示了如何使用Java发送一个包含参数的HTTP POST请求给服务器端点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值