以下代码展示了如何以POST方式向服务器发送数据并获取返回值。
package java1_javaProject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class HttpUrlConnectionEx {
public final String USER_AGENT="Mozilla/5.0";
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
HttpUrlConnectionEx huc=new HttpUrlConnectionEx();
System.out.println("\nTesting 2 - send Http POST request");
huc.sendPost();
}
private void sendPost() throws Exception{
String url ="http://localhost:7477/WebSite1/Default.cshtml";
URL obj=new URL(url);
HttpURLConnection con=(HttpURLConnection)((URLConnection)obj.openConnection());
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters="ID=qiuqiu";
con.setDoOutput(true);
OutputStreamWriter wr=new OutputStreamWriter(con.getOutputStream());
wr.write(urlParameters);
wr.flush();
wr.close();
int responseCode=con.getResponseCode();
System.out.println("\nSending 'POST' request to URL :"+url);
System.out.println("Post Parameters :"+urlParameters);
System.out.println("Response Code :"+responseCode);
BufferedReader in =new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response=new StringBuffer();
while((inputLine=in.readLine())!=null){
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}