java代码获取x-www-from-urlencoded格式json数据

今天碰到使用java获取x-www-from-urlencoded格式json数据,以前没用过记录一下。

public String getMsg() {
                try {
                      String postURL = "url地址";
                      PostMethod postMethod = null;
                      postMethod = new PostMethod(postURL) ;
                      postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
                      postMethod.setRequestBody("Authorization");
                    //参数设置,需要注意的就是里边不能传NULL,要传空字符串
                      NameValuePair[] data = {

                                //传递参数
                              new NameValuePair("username","账号"),
                              new NameValuePair("password","密码")            
                      };
                      postMethod.setRequestBody(data);
                      org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
                      int response = httpClient.executeMethod(postMethod); // 执行POST方法
                      String result = postMethod.getResponseBodyAsString() ;
                      return result;
                    } catch (Exception e) {
                      throw new RuntimeException(e.getMessage());
                    }
                }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中的application/x-www-form-urlencoded表单格式是一种用于在HTTP请求中发送数据的标准格式。它通常用于提交HTML表单数据,包括用于登录、注册、搜索、上传文件等操作。 在该格式中,表单数据以字符串键值对的形式组成,每个键值对之间用“&”号分隔。每个键值对由一个“=”号连接键和值,键和值都需要进行URL编码,以便安全地进行传输。 Java中可以使用URLEncoder来进行URL编码,使用URLDecoder进行解码。例如,要向服务器发送一个包含用户名和密码的表单数据,可以使用以下代码: ``` String username = "user@example.com"; String password = "mypassword"; String encodedData = "username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8"); URLConnection connection = new URL("https://example.com/login").openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(encodedData); out.close(); // 处理服务器响应... ``` 在服务器端,可以通过读取请求正文来获取表单数据。例如,在Java Servlet中,可以使用getParameter方法来获取表单数据: ``` String username = request.getParameter("username"); String password = request.getParameter("password"); ``` 总之,application/x-www-form-urlencoded格式是一种常用的HTTP请求数据格式Java提供了方便的工具来进行URL编解码。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值