Opening webpage in default browser with double-quotes (") inside url

走远了吗. 提交于 2019-12-12 09:39:36

问题


When I try to open any site that has double-quotes (") inside the link , for ex. user.php?name="stackoverflow" it just cuts " or sometimes it redirects me to Google!? Used code:

ShellExecute(0, 'open', PChar('open'), PChar(URL), nil, SW_SHOW) ;

回答1:


You need use a fully qualified URL including the http:// and escape/encode the URL by replacing the double-quotes (") with %22.

Also you are passing wrong parameters.

See MSDN: Use ShellExecute to launch the default Web browser

Example:

procedure TForm1.Button1Click(Sender: TObject);
var
  URL: string;
begin
  URL := 'http://www.user.com/?name="stackoverflow"';
  URL := StringReplace(URL, '"', '%22', [rfReplaceAll]);
  ShellExecute(0, 'open', PChar(URL), nil, nil, SW_SHOWNORMAL);
end;

You should always encode the URL parameters, not only double-quotes. You can use Indy with TIdURI.URLEncode - IdURI unit.
You could also use HTTPEncode from the HTTPApp unit to encode each parameter in the URL.

Note that TIdURI.URLEncode will encode the ? and the & separators also. so I think it's a better idea to encode each parameter separately with HTTPEncode e.g:

URL := 'http://www.user.com/?param1=%s&param2=%s';
URL := Format(URL, [
  HTTPEncode('"stackoverflow.com"'),
  HTTPEncode('hello word!')]);
// output: http://www.user.com/?param1=%22stackoverflow.com%22&param2=hello+word!


来源:https://stackoverflow.com/questions/10154543/opening-webpage-in-default-browser-with-double-quotes-inside-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!