added default content type

This commit is contained in:
Pablo Fernandez committed 2011-09-25 19:14:57 -03:00
1 parent 24babbae02
commit ae3a1b11c9
3 files changed
+52 -1

No files matched your search

@@ -17,6 +17,8 @@ import org.scribe.utils.*;
class Request
{
private static final String CONTENT_LENGTH = "Content-Length";
private static final String CONTENT_TYPE = "Content-Type";
public static final String DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded";
private String url;
private Verb verb;
@@ -108,6 +110,12 @@ class Request
void addBody(HttpURLConnection conn, byte[] content) throws IOException
{
conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(content.length));
// Set default content type if none is set.
if (conn.getRequestProperty(CONTENT_TYPE) == null)
{
conn.setRequestProperty(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
}
conn.setDoOutput(true);
conn.getOutputStream().write(content);
}
@@ -22,6 +22,12 @@ public class ConnectionStub extends HttpURLConnection
headers.put(key, value);
}
@Override
public String getRequestProperty(String s)
{
return headers.get(s);
}
public Map<String, String> getHeaders()
{
return headers;
@@ -6,7 +6,6 @@ import org.junit.*;
public class RequestTest
{
private Request getRequest;
private Request postRequest;
private ConnectionStub connection;
@@ -80,4 +79,42 @@ public class RequestTest
{
assertTrue(getRequest.getQueryStringParams().get("other param").equals("value with spaces"));
}
@Test
public void shouldAutomaticallyAddContentTypeForPostRequestsWithBytePayload()
{
postRequest.addPayload("PAYLOAD".getBytes());
postRequest.send();
assertEquals(Request.DEFAULT_CONTENT_TYPE, connection.getHeaders().get("Content-Type"));
}
@Test
public void shouldAutomaticallyAddContentTypeForPostRequestsWithStringPayload()
{
postRequest.addPayload("PAYLOAD");
postRequest.send();
assertEquals(Request.DEFAULT_CONTENT_TYPE, connection.getHeaders().get("Content-Type"));
}
@Test
public void shouldAutomaticallyAddContentTypeForPostRequestsWithBodyParameters()
{
postRequest.send();
assertEquals(Request.DEFAULT_CONTENT_TYPE, connection.getHeaders().get("Content-Type"));
}
@Test
public void shouldBeAbleToOverrideItsContentType()
{
postRequest.addHeader("Content-Type", "my-content-type");
postRequest.send();
assertEquals("my-content-type", connection.getHeaders().get("Content-Type"));
}
@Test
public void shouldNotAddContentTypeForGetRequests()
{
getRequest.send();
assertFalse(connection.getHeaders().containsKey("Content-Type"));
}
}