-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpostRequest.java
More file actions
72 lines (59 loc) · 2.55 KB
/
Copy pathpostRequest.java
File metadata and controls
72 lines (59 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class PostRequest {
/*Note: This code example requires Base64Coder file which is
available below in the Dependencies section.*/
public static void main(String[] args) {
String APIKey = "YOUR_API_KEY";
String TeamworkURL = "https://YOUR_TEAMWORK_SITE_NAME.teamwork.com";
String tasklistID = "TASK_LIST_ID";
String taskName = "This is an example task created via a POST request in Java.";
String action = "/todo_lists/" + tasklistID + "/todo_items.json";
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = new Date();
String dueDate = dateFormat.format(date);
String json = "{\"todo-item\":{\"content\":\""
+taskName+"\",\"due-date\":\""+dueDate+"\"}}";
try {
URL url = new URL( TeamworkURL + action );
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
String userpassword = APIKey + ":xxx";
String encodedAuthorization = Base64Coder.encodeString( userpassword );
connection.setRequestProperty("Authorization", "BASIC "
+ encodedAuthorization);
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write(json);
osw.flush();
osw.close();
InputStream _is;
if (connection.getResponseCode() != 201) {
/* error */
errorStream = connection.getErrorStream();
System.out.println( streamToString(errorStream) );
}
InputStream responseStream = connection.getInputStream();
System.out.println( streamToString( responseStream) );
} catch(Exception e) {
System.out.println( "Error Received:" + e.getMessage() );
}
}
public static String streamToString(InputStream in) throws IOException {
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
for(String line = br.readLine(); line != null; line = br.readLine())
out.append(line);
br.close();
return out.toString();
}
}