Skip to content

Instantly share code, notes, and snippets.

@magicsih
Last active May 30, 2017 07:08
Show Gist options
  • Save magicsih/bb1867a31cee57971ec59d5288a1021f to your computer and use it in GitHub Desktop.
Save magicsih/bb1867a31cee57971ec59d5288a1021f to your computer and use it in GitHub Desktop.
Simple Java HTTP Client Code Snippet for KeepAliveTesting
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
class KeepAliveTest {
public static void main(String[] args) throws IOException {
while(true) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
long start = System.currentTimeMillis();
URL url = new URL("http://172.27.1.25:5007/device/event/inputkeyevent");
System.out.println("makeHTTPUrlConnection - " + url.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/json");
conn.setRequestProperty("Accept", "application/json");
ByteBuffer byteBuf = ByteBuffer.wrap("{\"code\":3}".getBytes());
try(WritableByteChannel channel = Channels.newChannel(conn.getOutputStream())) {
System.out.println("Connect : " + (System.currentTimeMillis()-start) + "ms");
channel.write(byteBuf);
System.out.println("Request : " + (System.currentTimeMillis()-start) + "ms");
}
String body = null;
try (BufferedInputStream in = new BufferedInputStream(conn.getInputStream())) {
System.out.println("Response : " + (System.currentTimeMillis()-start) + "ms");
System.out.println(System.currentTimeMillis()-start + "ms");
System.out.println("Status:"+conn.getResponseCode());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] byteArr= new byte[1024*8];
int length = 0;
while ((length = in.read(byteArr)) != -1) {
out.write(byteArr, 0, length);
}
body = new String(out.toByteArray(),"UTF-8");
} catch(IOException e){
InputStream errorStream = conn.getErrorStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] byteArr= new byte[1024*8];
int length = 0;
while ((length = errorStream.read(byteArr)) != -1) {
out.write(byteArr, 0, length);
}
body = new String(out.toByteArray(),"UTF-8");
e.printStackTrace();
}
System.out.println(body);
System.out.println("Total:" + (System.currentTimeMillis()-start) + "ms");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment