java实现网络交互 get、post方法(二)

2014-11-24 07:14:25 · 作者: · 浏览: 1
on.setDoInput(true); con.setDoOutput(true);//指示应用程序要将数据写入 URL 连接。 String content = getContent(params);//解析参数(请求的内容) con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置内容 con.setRequestProperty("Content-Length", content.length()+"");//设置内容长度 OutputStream os = con.getOutputStream(); os.write(content.getBytes("utf-8"));//发送参数内容 os.flush(); os.close(); if(con.getResponseCode() == 200){ str = formatIsToString(con.getInputStream()); } return str; }
将map里的参数进行解析
private static String getContent(HashMap
   
     params) throws UnsupportedEncodingException {
		String content = null;
		Set
    
     > set = params.entrySet();//Map.entrySet 方法返回映射的 collection 视图,其中的元素属于此类 StringBuilder sb = new StringBuilder(); for(Entry
     
       i: set){//将参数解析为"name=tom&age=21"的模式 sb.append(i.getKey()).append("=") .append(URLEncoder.encode(i.getValue(), "utf-8")) .append("&"); } if(sb.length() > 1){ content = sb.substring(0, sb.length()-1); } return content; }
     
    
   
用Entry的好处是不用知道key的值可以通过getKey()和getValue()方法得到map中的所有值