Package com.andrew.study.http;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import java.net.URLConnection;
Import java.util.List;
Import Java.util.Map;
public class Httputil {
Single parameter
public static string Sendget (string url, string param) {
String urlstr = URL + "?" + param;
String result = "";
BufferedReader in = null;
try {
URL realurl = new URL (urlstr);
URLConnection connection = Realurl.openconnection ();
To set common request properties
Connection.setrequestproperty ("Accept", "*/*");
Connection.setrequestproperty ("Connection", "keep-alive");
Connection.setrequestproperty ("User-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ");
Connection.connect ();
/* Get all the request headers
* map<string, list<string>> heads = Connection.getheaderfields ();
For (String Key:heads.keySet ()) {
SYSTEM.OUT.PRINTLN (key + "--->" + heads.get (key));
}*/
in = new BufferedReader (New InputStreamReader (Connection.getinputstream ()));
String line = "";
while (line = In.readline ()) = null) {
result + = line;
}
} catch (Exception e) {
E.printstacktrace ();
} finally {
if (in = null) {
try {
In.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}
return result;
}
public static string Sendpost (string url, string param) {
PrintWriter out = null;
BufferedReader reader = null;
String result = "";
try {
URL realurl = new URL (URL);
URLConnection connection = Realurl.openconnection ();
To set common request properties
Connection.setrequestproperty ("Accept", "*/*");
Connection.setrequestproperty ("Connection", "keep-alive");
Connection.setrequestproperty ("User-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ");
The POST request must have these two items set
Connection.setdooutput (TRUE);
Connection.setdoinput (TRUE);
Connection.connect ();
Get URLConnection output stream
out = new PrintWriter (Connection.getoutputstream ());
Send Request parameters
Out.print (param);
Refresh Cache
Out.flush ();
To read a URL response using the Bufferreader input stream
reader = new BufferedReader (New InputStreamReader (Connection.getinputstream ()));
String Line;
while (line = Reader.readline ()) = null) {
result + = line;
}
} catch (Exception e) {
E.printstacktrace ();
} finally {
try {
if (reader! = null) {
Reader.close ();
}
} catch (Exception E2) {
E2.printstacktrace ();
}
}
return result;
}
public static void Main (string[] args) {
String string = Sendget ("http://www.baidu.com", "");
System.out.println (Sendpost ("Http://localhost:8080/hello1", ""));
}
}
Java public class--http request