1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.christianschenk.confluence.plugin.bibsonomy.helper;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.util.Scanner;
24
25 import org.apache.commons.httpclient.Credentials;
26 import org.apache.commons.httpclient.HttpClient;
27 import org.apache.commons.httpclient.URI;
28 import org.apache.commons.httpclient.UsernamePasswordCredentials;
29 import org.apache.commons.httpclient.auth.AuthScope;
30 import org.apache.commons.httpclient.methods.GetMethod;
31 import org.apache.commons.httpclient.params.HttpClientParams;
32 import org.dom4j.Document;
33 import org.dom4j.DocumentException;
34 import org.dom4j.io.SAXReader;
35
36 import static org.christianschenk.confluence.plugin.bibsonomy.helper.ValidationUtils.present;
37
38
39
40
41
42
43 public class HttpClientHelper {
44
45 private final String username;
46 private final String password;
47
48 public HttpClientHelper() {
49 this(null, null);
50 }
51
52 public HttpClientHelper(final String username, final String password) {
53 this.username = username;
54 this.password = password;
55 }
56
57 public String getString(final String url) {
58 final Scanner scan = new Scanner(this.get(url));
59 final StringBuffer buf = new StringBuffer();
60 while (scan.hasNextLine()) buf.append(scan.nextLine()+"\n");
61 return buf.toString();
62 }
63
64 public Document getDocument(final String url) {
65 try {
66 return new SAXReader().read(this.get(url));
67 } catch (final DocumentException ex) {
68 throw new RuntimeException(ex);
69 }
70 }
71
72 private InputStream get(final String url) {
73 final HttpClientParams params = new HttpClientParams();
74 params.setSoTimeout(5000);
75 params.setConnectionManagerTimeout(5000);
76 final HttpClient httpClient = new HttpClient(params);
77
78 if (present(this.username) == true) {
79 final Credentials defaultcreds = new UsernamePasswordCredentials(this.username, this.password);
80 httpClient.getState().setCredentials(AuthScope.ANY, defaultcreds);
81 }
82
83 try {
84 final GetMethod method = new GetMethod();
85 method.setURI(new URI(url, false));
86 httpClient.executeMethod(method);
87 return method.getResponseBodyAsStream();
88 } catch (final IOException ex) {
89 throw new RuntimeException(ex);
90 }
91 }
92 }