java裏 http協議的 post請求

public class UrlUrlconnection {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String url="http://www.baidu.com/s";
String param="wd=java";
System.out.println(sendHttpPost(url, param));
}

public static String sendHttpPost(String url,String param){
String result="";
try {
URL httpUrl=new URL(url);
HttpURLConnection huc=(HttpURLConnection) httpUrl.openConnection();
huc.setDoOutput(true);//設置可以向httpurlConnection 裏面輸出
huc.setDoInput(true);//設置可以向httpurlConnection 裏面輸入
huc.setUseCaches(false);//post請求不能使用緩存
huc.setRequestMethod("POST");//設置爲Post 請求
PrintWriter pw=new PrintWriter(huc.getOutputStream());
pw.write(param);
pw.flush();
pw.close();
BufferedReader br=new BufferedReader(new InputStreamReader(huc.getInputStream(),"utf-8"));
while(br.readLine()!=null){
result+="\n"+br.readLine();
//System.out.println(br.readLine());
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章