Issues unit testing connection to URI
I'm unit testing my Java/Jersey web service and running into an interesting test case. I'm checking the status codes of different URI entries to make sure that incorrect URIs won't destroy my code or anything. In test cases where I throw in invalid characters (such as !@$#<>, etc.), my browser pulls up a 404 error like I would expect, but JUnit is showing the error as a 500 error. This happens in cases where I throw in things like "<134->" and cases where I try injecting html code (such as "myURI<html><p>hello</p><br></html>/restofmyURI
").
Any ideas why I would be getting different server respo开发者_Python百科nses for the same call, and/or how to consolidate the responses?
Just want to tie up loose ends for my process here. I ended up not needing to encode my tests since the URLs would be called directly, not through a browser, but I had an encoding method in place before I realized that. Based upon Kaj's suggestion (see comments on my original question), I encoded the string in parts, splitting at any characters I needed to leave unencoded (namely :
and /
for this case). It's a bit more complicated than I feel it needs to be, but it served its purpose.
--Edit: Relevant Code--
Here is the method of my test which I call to open a connection to the server (using basic authentication):
private void getConnection(String target, String user, String pass) throws Exception
{
URL url = new URL(target);
URLConnection conn = url.openConnection();
//Here's where basic auth kicks in
String creds = user + ":" + pass;
String encoded = new sun.misc.BASE64Encoder().encode(creds.getBytes());
conn.setRequestProperty("Authorization", "Basic " + encoded);
//This part doesn't rely on authentication
conn.connect();
}
The encoding (if necessary) would be done before being passed into this method.
Instead of encoding the String
directly, encode
the url
object:
That should help prevent the MalformedURLException
:
try {
URL url = new URL("http://myurl/otherparameters/here");
String encodedurl = URLEncoder.encode(url.toString(),"UTF-8");
} catch(MalformedURLException mue) {
System.err.println(mue);
} catch(UnsupportedEncodingException uee) {
System.err.println(uee);
}
精彩评论