Skip to content

Commit

Permalink
Fixes #97 by calling the correct setXxx method in HttpHeaders determi…
Browse files Browse the repository at this point in the history
…ned through reflection
  • Loading branch information
varontron committed Nov 1, 2018
1 parent 306d6a8 commit b6fae4e
Showing 1 changed file with 30 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpCookie;
import java.net.URL;
import java.net.URLConnection;
Expand Down Expand Up @@ -429,7 +431,7 @@ private void setCookies(YADAQuery yq, HttpRequest request)
{
cookieStr += cookie.getName()+"="+cookie.getValue()+";";
}
HttpHeaders headers = new HttpHeaders();
HttpHeaders headers = request.getHeaders();
headers.setCookie(cookieStr);
request.setHeaders(headers);
}
Expand All @@ -440,13 +442,15 @@ private void setCookies(YADAQuery yq, HttpRequest request)
* and adds them to the {@link HttpRequest}
* @param yq the {@link YADAQuery} object
* @param request the HttpRequest object
* @throws YADAQueryConfigurationException
* @since 8.7.0
*/
private void setHeaders(YADAQuery yq, HttpRequest request)
private void setHeaders(YADAQuery yq, HttpRequest request) throws YADAQueryConfigurationException
{
if(yq.getHttpHeaders() != null && yq.getHttpHeaders().length() > 0)
{
HttpHeaders headers = new HttpHeaders();
HttpHeaders headers = request.getHeaders();

l.debug("Processing custom headers...");
@SuppressWarnings("unchecked")
Iterator<String> keys = yq.getHttpHeaders().keys();
Expand All @@ -455,7 +459,29 @@ private void setHeaders(YADAQuery yq, HttpRequest request)
String name = keys.next();
String value = yq.getHttpHeaders().getString(name);
l.debug("Custom header: "+name+" : "+value);
headers.set(name, value);

String method = "set"+name.replace("-","");
try
{
Class<HttpHeaders> clazz = HttpHeaders.class;
Method meth = clazz.getMethod(method, java.lang.String.class);
meth.invoke(headers, value);
}
catch (NoSuchMethodException|SecurityException e)
{
String msg = "There is no method named ["+method+"]. It could be a case issue."
+ "Method names are camel-cased, and header names should have initial "
+ " caps, and hyphens instead of spaces.";
l.warn(msg);
l.warn("Trying to use generic setter");
headers.set(name, value);
}
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
{
String msg = "The ["+name+"] header could not be set.";
throw new YADAQueryConfigurationException(msg, e);
}
request.setHeaders(headers);
}
}
}
Expand Down

0 comments on commit b6fae4e

Please sign in to comment.