Thursday, November 19, 2015

Java output raw http get post

The following shows how Java write raw http GET and POST request via socket.

// Break down destinationURL.
// Reference: http://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html
java.net.URL aURL = new java.net.URL(destinationURL);
String sProtocol = aURL.getProtocol();
String sHost = aURL.getHost();
int iPort = aURL.getPort();
if (iPort == -1) {
  if (sProtocol.equals("https")) {
    iPort = 443;
  } else {
    iPort = 80;
  }
}
String sPath = aURL.getPath();
String sQuery = aURL.getQuery();
if (sQuery == null) { sQuery = parameters; } else { sQuery = sQuery + "&" + parameters; }

// Create socket.
java.net.Socket clientSocket;
if (sProtocol.equalsIgnoreCase("https")) {
   clientSocket = SSLSocketFactory.getDefault().createSocket(sHost,iPort);
} else {
   clientSocket = new java.net.Socket(sHost,iPort);
}
clientSocket.setSoTimeout(Integer.parseInt(timeOut));
 
// Connect to server.
java.io.OutputStream output = clientSocket.getOutputStream();
//output.write(("GET " + sPath + "?" + sQuery + " HTTP/1.1\r\n").getBytes("UTF-8"));
//output.write(("Host: " + sHost + "\r\n").getBytes("UTF-8"));
//output.write("Connection: close\r\n".getBytes("UTF-8")); // So the server will close socket immediately.
//output.write("\r\n".getBytes("UTF-8")); // HTTP1.1 requirement: last line must be empty line.
output.write(("POST " + sPath + " HTTP/1.1\r\n").getBytes("UTF-8"));
output.write(("Host: " + sHost + "\r\n").getBytes("UTF-8"));
output.write(("Content-Type: application/x-www-form-urlencoded\r\n").getBytes("UTF-8"));
output.write(("Content-Length: " + sQuery.length() + "\r\n").getBytes("UTF-8"));
output.write(("Connection: close\r\n").getBytes("UTF-8")); // So the server will close socket immediately.
output.write(("\r\n" + sQuery).getBytes("UTF-8"));
output.flush();

java.io.InputStream in = clientSocket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String inputLine = "";
while ((inputLine = reader.readLine()) != null) {
   response.append(inputLine);
}
System.out.println("HTTP Response = [" + response + "]");

Dynamic way to compose http parameters:
http://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily

String userpass = org.apache.commons.codec.binary.Base64.encodeBase64("username:password".getBytes("UTF-8"))

import java.io.*;
import java.net.*;
import java.util.*;

class Test {
    public static void main(String[] args) throws Exception {
        URL url = new URL("http://example.net/new-message.php");
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("name", "Freddie the Fish");
        params.put("email", "fishie@seamail.example.com");
        params.put("reply_to_thread", 10394);
        params.put("message", "Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He's so shellfish.");

        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String,Object> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setRequestProperty("Authorization", "Basic ${userpass}")        
conn.setDoOutput(true); conn.getOutputStream().write(postDataBytes); Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); for (int c; (c = in.read()) >= 0;) System.out.print((char)c); } }



 

No comments: