使用post的方式发送http请求

/**
* 使用post的方式发送http请求  
* @param uri  请求资源路径
* @param params  请求参数
* @return
* @throws MalformedURLException 
*/
public static InputStream postInputStream(String uri, Map<String, String> params) throws IOException{
URL url = new URL(uri);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置参数
StringBuilder param=new StringBuilder();
Set<String> keySet = params.keySet();
Iterator<String> ite = keySet.iterator();
while(ite.hasNext()){
String key=ite.next();
String val=params.get(key);
param.append(key+"="+val+"&");
}
//param:    a=b&c=d&
param.deleteCharAt(param.length()-1);
//传递参数
OutputStream os = conn.getOutputStream();
os.write(param.toString().getBytes("utf-8"));
os.flush();
//获取输入流
return conn.getInputStream();
}

你可能感兴趣的:(使用post的方式发送http请求)