• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

yxchun

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

发送get请求报错, Exception in thread "main" java.lang.IllegalArgumentException: Illegal character in query at index 103

处理url,发送get请求时报错;

解决方法:利用 URLEncoder.encode("参数","UTF-8");方法对参数进行转化

String paramAfter = URLEncoder.encode("参数","UTF-8");
然后再将
paramAfter 拼接到url里面;
 url += "&" + key + "=" + paramAfter;
 

原因:

 

例子:

    public static String doGet(String params, String url) throws UnsupportedEncodingException {
        String result="";
        if(params!=null && params.length()>0){
            // 》0说明有参数
            Map<String,Object> paramMap= (Map<String, Object>) JSONObject.parse(params);
            int target = 1;
            for(String key : paramMap.keySet()){
                // 判断是否为第一个参数
                if (target == 1) {
                    url += "?" + key + "=" +  URLEncoder.encode((paramMap.get(key)).toString(),"UTF-8");
                } else {

                    url += "&" + key + "=" + URLEncoder.encode((paramMap.get(key)).toString(),"UTF-8");

                }
                target++;
            }
        }
        try{

            HttpGet get = new HttpGet(url);


            //        设置请求超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000)
                    .setConnectionRequestTimeout(3000)
                    .setSocketTimeout(3000)
                    .build();
            get.setConfig(requestConfig);

            // 添加token
            addTokenInRequest(get);

            CloseableHttpResponse httpResponse = trustAll().execute(get);
            //返回结果
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            String postReturn = EntityUtils.toString(httpResponse.getEntity());
            result = "code=" + statusCode + ",result = " + postReturn;
        }catch (IOException  e){
            e.printStackTrace();
        }
        return result;
    }

 

 

posted on 2024-08-06 14:56  yxchun  阅读(168)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3