HTTP提交数据

 1     /**
 2      * 将放入的参数转换成POST的形式key=value
 3      * @param parames
 4      * @param encode
 5      * @return
 6      */
 7     public static String sendPostMessage(Map<String,String> parames,String encode){
 8         
 9         StringBuffer buffer=new StringBuffer();
10         try{
11         
12         if(parames!=null&&!parames.isEmpty())
13         {
14             for(Map.Entry<String, String> entry:parames.entrySet()){
15                 buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&");
16             }
17         }
18         return sendOutput(buffer.toString());
19         }catch(Exception e){
20             
21         }
22         return null;
23         
24     }
25     /**
26      * @param outputStream 传入的要输出的对象的流
27      * @param data 获取发送的数据
28      * @return 
29      */
30     private static String sendOutput(String data){
31         try{
32             byte[] mydata=data.getBytes();
33             URL url=new URL(URL_path);
34             HttpURLConnection connection=(HttpURLConnection)url.openConnection();
35             connection.setConnectTimeout(3000);
36             connection.setDoInput(true);
         connection.setDoOutput(true);
         //设置提交数据方式
         connection.setRequestMethod("POST");
37 //设置手机端访问服务器端时请求头信息(http协议) 38 //设置请求的类型为文本类型 39 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 40 //设置请求体的长度 41 connection.setRequestProperty("Content-Length", String.valueOf(mydata.length)); 42 43 OutputStream outputStream=connection.getOutputStream(); 44 outputStream.write(mydata); 45 46 return changeInputStream(connection.getInputStream(), "utf-8"); 47 48 }catch(Exception e){ 49 50 } 51 return null; 52 } 53 54 /** 55 * 强输入流转换为字符串输出到内存 56 * @param inputStream 57 * @param encode 58 * @return 59 */ 60 private static String changeInputStream(InputStream inputStream,String encode){ 61 ByteArrayOutputStream outputStream=new ByteArrayOutputStream(); 62 byte[] buffer=new byte[1024]; 63 int length=0; 64 try { 65 while(-1!=(length=inputStream.read(buffer))){ 66 outputStream.write(buffer, 0, length); 67 } 68 return new String(outputStream.toByteArray(), "encode"); 69 } catch (IOException e) { 70 // TODO Auto-generated catch block 71 e.printStackTrace(); 72 } 73 74 return null; 75 } 76 public static void main(String[] args) { 77 Map<String, String> parames=new HashMap<String,String>(); 78 parames.put("username", "admin"); 79 parames.put("password", "admin"); 80 sendPostMessage(parames, "utf-8"); 81 } 82 }

 

posted on 2016-04-18 12:30  oldcowstruggle  阅读(206)  评论(0编辑  收藏  举报