Skip to content

Commit 6f4b447

Browse files
committed
created addHeader method
You can now add a request header. Useful for API keys.
1 parent 5340dad commit 6f4b447

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

src/http/requests/GetRequest.java

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
package http.requests;
22

3+
import java.util.ArrayList;
4+
import java.util.Iterator;
5+
36
import org.apache.http.Header;
47
import org.apache.http.HttpEntity;
58
import org.apache.http.HttpResponse;
9+
import org.apache.http.NameValuePair;
610
import org.apache.http.auth.UsernamePasswordCredentials;
711
import org.apache.http.client.methods.HttpGet;
812
import org.apache.http.impl.auth.BasicScheme;
913
import org.apache.http.impl.client.DefaultHttpClient;
14+
import org.apache.http.message.BasicNameValuePair;
1015
import org.apache.http.util.EntityUtils;
1116

1217
public class GetRequest
@@ -15,17 +20,28 @@ public class GetRequest
1520
String content;
1621
HttpResponse response;
1722
UsernamePasswordCredentials creds;
23+
ArrayList<BasicNameValuePair> headerPairs;
1824

25+
1926
public GetRequest(String url)
2027
{
2128
this.url = url;
29+
headerPairs = new ArrayList<BasicNameValuePair>();
30+
2231
}
2332

2433
public void addUser(String user, String pwd)
2534
{
2635
creds = new UsernamePasswordCredentials(user, pwd);
27-
}
28-
36+
37+
}
38+
39+
public void addHeader(String key,String value) {
40+
BasicNameValuePair nvp = new BasicNameValuePair(key,value);
41+
headerPairs.add(nvp);
42+
43+
}
44+
2945
public void send()
3046
{
3147
try {
@@ -37,6 +53,13 @@ public void send()
3753
httpGet.addHeader(new BasicScheme().authenticate(creds, httpGet, null));
3854
}
3955

56+
Iterator<BasicNameValuePair> headerIterator = headerPairs.iterator();
57+
while (headerIterator.hasNext()) {
58+
BasicNameValuePair headerPair = headerIterator.next();
59+
httpGet.addHeader(headerPair.getName(),headerPair.getValue());
60+
}
61+
62+
4063
response = httpClient.execute( httpGet );
4164
HttpEntity entity = response.getEntity();
4265
this.content = EntityUtils.toString(response.getEntity());

0 commit comments

Comments
 (0)