Sunday, January 1, 2017

Java Post JSON data

GSON library is good tool to convert data to JSON format 1. Add GSON dependency, current latest version is 2.8.0
1
2
3
4
5
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.0</version>
</dependency>
2. The data sender util look like:
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
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
 
import com.google.gson.Gson;
 
public class HttpRequestSender {
 
    private static final Logger LOGGER = Logger.getLogger(HttpRequestSender.class.getName());
 
    public static int postJsonData(String url, Object data, int connectionTimeout, int readTimeout, StringBuffer response) {
        int responseCode = 0;
        Gson gson = new Gson();
        StringBuilder sb = new StringBuilder();
        sb.append("data=").append(gson.toJson(data));
        long startTime = System.currentTimeMillis();
        try {
            URL urlObj = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
            conn.setConnectTimeout(connectionTimeout);
            conn.setReadTimeout(readTimeout);
            conn.setRequestMethod("POST");
            conn.setInstanceFollowRedirects(false);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("charset", "UTF-8");
            byte[] postData = sb.toString().getBytes("UTF-8");
            conn.setRequestProperty("content-length", postData.length + "");
            conn.setDoOutput(true);
            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                wr.write(postData);
                wr.flush();
            }
            responseCode = conn.getResponseCode();
            if (response != null) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                    String line = reader.readLine();
                    while (line != null) {
                        response.append(line);
                        line = reader.readLine();
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Error while posting data " + String.valueOf(data) + " to " + url, e);
        }
        LOGGER.log(Level.INFO, "Posted {0} to {1} took {2} ms", new Object[] { String.valueOf(data), url, (System.currentTimeMillis() - startTime) });
        return responseCode;
    }
}

How To Get Source IP Address from HttpServletRequest

The address of source of request is stored in the header of HttpServletRequest so it is simply to get it. If it is not available in header so we can get the RemoteAddress. Mark dependency to package javaee-web-api, current latest verion is 7.0
1
2
3
4
5
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-web-api</artifactId>
    <version>7.0</version>
</dependency>
The util look like:
1
2
3
4
5
6
7
8
9
10
public static String getSourceIPAddress(HttpServletRequest request) {
    String srcIPAddress = request.getHeader("X-FORWARDED-FOR");
    if (srcIPAddress == null) {
        srcIPAddress = request.getRemoteAddr();
    }
    if (srcIPAddress != null && srcIPAddress.contains(",")) {
        srcIPAddress = srcIPAddress.split(",")[0];
    }
    return srcIPAddress;
}