These are the methods I use to evaluate
$$
\int_0^{\infty}\frac{\cos2x}{x^2+4}\,dx
$$
and post it on Brilliant.org as a solution of similar problem. You can use the similar technique to evaluate
$$
\int_0^{\infty}\frac{\cos x}{x^2+1}\,dx.
$$

The previous answer is not correct. If you use the Taylor expansion of cosine and integrate termwise you consider integrals of the following form:
\begin{eqnarray}
\int_{0}^{\infty} \frac{x^{a} \ dx}{1 + x^{2}} = \tfrac{\pi}{2} \sec (\tfrac{\pi a}{2})
\end{eqnarray}
which is only well-defined if $-1 < a < 1$.