· 9 years ago · Dec 08, 2016, 05:18 PM
1import java.io.BufferedReader;
2
3import java.io.InputStreamReader;
4
5import java.time.LocalDateTime;
6
7
8import javax.crypto.Mac;
9import javax.crypto.spec.SecretKeySpec;
10
11import org.apache.commons.codec.binary.Hex;
12import org.apache.http.Header;
13import org.apache.http.HttpEntity;
14import org.apache.http.client.methods.*;
15import org.apache.http.entity.ContentType;
16import org.apache.http.entity.StringEntity;
17import org.apache.http.impl.client.CloseableHttpClient;
18import org.apache.http.impl.client.HttpClients;
19import org.apache.http.util.EntityUtils;
20
21------------------------------------------------------------------------
22
23public static void post() throws Exception{
24
25 CloseableHttpClient httpclient = HttpClients.createDefault();
26
27 try{
28 // POST
29 HttpPost httpPost = new HttpPost("https://testservices.informatsoftware.be/icursisten/1/course/42CD5A20-E22F-45D7-973C-FAB8734DEC50");
30
31 httpPost.setEntity(new StringEntity("",
32 ContentType.create("application/json")));
33 CloseableHttpResponse response2 = httpclient.execute(httpPost);
34
35 //httpPost.
36
37 httpPost.addHeader("InstellingsNr", "128521");
38 httpPost.addHeader("Authentication","pubKey_HbKycQkxTipifyplssirJPQZxEHFbL" + ":" + encode("zmHnwWgjWj37H5yjm1Or1MtfLyRPoYcwJytE4VV5Y6E1Ep0BpSpQ7048tNLp3RxcJlq5H4", ""));
39 httpPost.addHeader("Timestamp", LocalDateTime.now().toString());
40 httpPost.addHeader("Accept","application/json");
41 httpPost.addHeader("Content-Typet","application/json");
42 httpPost.addHeader("Content-Length","0");
43
44 try {
45 System.out.println("Request headers: \n");
46 for(Header hdr : httpPost.getAllHeaders()){
47 System.out.println("\t" + hdr.toString());
48 }
49
50 System.out.println("\n\nResult: \n");
51
52 System.out.println("\t" + response2.getStatusLine());
53 HttpEntity entity2 = response2.getEntity();
54 // do something useful with the response body
55 // and ensure it is fully consumed
56 BufferedReader in = new BufferedReader(
57 new InputStreamReader(entity2.getContent()));
58 String inputLine;
59 StringBuffer response = new StringBuffer();
60
61 while ((inputLine = in.readLine()) != null) {
62 response.append(inputLine);
63 }
64 in.close();
65
66 //print result
67 System.out.println("\t" + "Response : " + response.toString());
68 EntityUtils.consume(entity2);
69 }
70 finally {
71 response2.close();
72 System.out.println("**********************************");
73 }
74 }finally{
75 httpclient.close();
76 }
77 }
78
79 public static String encode(String key, String data) throws Exception {
80 Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
81 SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
82 sha256_HMAC.init(secret_key);
83
84 return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
85 }
86
87 public static void main(String[] args) throws Exception {
88 post();
89
90 }