forked from mthli/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostTest.java
More file actions
70 lines (64 loc) · 2 KB
/
PostTest.java
File metadata and controls
70 lines (64 loc) · 2 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
package post;
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
/**
* This program demonstrates how to use the URLConnection class for a POST request.
* @version 1.30 2012-06-04
* @author Cay Horstmann
*/
public class PostTest
{
public static void main(String[] args) throws IOException
{
Properties props = new Properties();
try (InputStream in = Files.newInputStream(Paths.get(args[0])))
{
props.load(in);
}
String url = props.remove("url").toString();
String result = doPost(url, props);
System.out.println(result);
}
public static String doPost(String urlString, Map<Object, Object> nameValuePairs)
throws IOException
{
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
try (PrintWriter out = new PrintWriter(connection.getOutputStream()))
{
boolean first = true;
for (Map.Entry<Object, Object> pair : nameValuePairs.entrySet())
{
if (first) first = false;
else out.print('&');
String name = pair.getKey().toString();
String value = pair.getValue().toString();
out.print(name);
out.print('=');
out.print(URLEncoder.encode(value, "UTF-8"));
}
}
StringBuilder response = new StringBuilder();
try (Scanner in = new Scanner(connection.getInputStream()))
{
while (in.hasNextLine())
{
response.append(in.nextLine());
response.append("\n");
}
}
catch (IOException e)
{
if (!(connection instanceof HttpURLConnection)) throw e;
InputStream err = ((HttpURLConnection) connection).getErrorStream();
if (err == null) throw e;
Scanner in = new Scanner(err);
response.append(in.nextLine());
response.append("\n");
}
return response.toString();
}
}