Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import java.net.HttpURLConnection;
Import Java.net.URL;
Import Java.util.HashMap;
Import Java.util.Map;
Public final class HttpClient {
public static final String http_method_post = "POST";
public static final String http_method_get = "GET";
public static final String http_method_put = "PUT";
public static final String http_method_delete = "DELETE";
public static final Integer connect_time_out = 10000;
public static HttpClient Create (URL url) {
return new HttpClient (URL);
}
URL Murl;
String Mmethod = Http_method_get;
String mdata = "";
Map<string, string> Mpropertys;
HttpClient (url url) {
Murl = URL;
Mpropertys = new hashmap<string, string> ();
}
Public synchronized void Setrequestmethod (String method) {
if (method = = NULL | | "". Equals (method))
Return
if (http_method_post = = METHOD | | Http_method_get = = METHOD
|| Http_method_put = = METHOD | | Http_method_delete = = METHOD) {
Mmethod = method;
}
}
Public synchronized void Setrequestdata (String data) {
if (data = = NULL)
Return
Mdata = data;
}
Public synchronized void Setrequestproperty (string name, String value) {
if (name = = NULL | | "". Equals (name) | | Value = = NULL
|| "". Equals (value))
Return
Mpropertys.put (name, value);
}
Public synchronized String execute () throws IOException {
Return execute ("Utf-8", connect_time_out);
}
Public synchronized string execute (String encode) throws IOException {
Return execute (encode,connect_time_out);
}
Public synchronized string Execute (string Encode,integer timeout) throws IOException {
HttpURLConnection conn = (httpurlconnection) murl.openconnection ();
Conn.setrequestmethod (Mmethod);
Conn.setdoinput (TRUE);
Conn.setconnecttimeout (timeout);
if (http_method_post = = Mmethod) {
Conn.setrequestproperty ("Content-type", "Application/json");
Conn.setdooutput (TRUE);
Conn.setrequestproperty ("Content-length",
String.valueof (Mdata.getbytes (). length));
Conn.getoutputstream (). Write (Mdata.getbytes (encode));
}
int code = Conn.getresponsecode ();
System.out.println ("****code:" +code);
if (code = = HTTPURLCONNECTION.HTTP_OK) {
InputStreamReader ISR = new InputStreamReader (
Conn.getinputstream (), encode);
BufferedReader in = new BufferedReader (ISR);
StringBuffer sbuf = new StringBuffer ();
String inputline = null;
while ((Inputline = In.readline ()) = null) {
Sbuf.append (Inputline);
}
return sbuf.tostring ();
}
return null;
}
public static void Main (string[] args) {
try {
String temp= "{\" username\ ": \" test\ ", \" password\ ": \" 123\ "}"; JSON data
HttpClient http = new HttpClient (New URL (
"http://...");
Http.setrequestmethod (Httpclient.http_method_post);
Http.setrequestdata (temp);
String respcode = new String (Http.execute ());
System.out.println ("****finished,respcode:" + respcode);
} catch (Exception e) {
System.out.println (e);
}
}
}
Simple HTTP request Test tool (support Get,post)