簡單的一個HttpUrlConnect的post請求



         public static String postUrlConnect(String urlPath, Map<String,Object> map){
                    StringBuffer sbRequest =new StringBuffer();
                     if(map!=null&&map.size()>0){
                         for (String key:map.keySet()){
                             sbRequest.append(key+"="+map.get(key)+"&");
                         }
                     }
                     String request = sbRequest.substring(0,sbRequest.length()-1);
                     try {
                         //創建URL
                         URL url = new URL(urlPath);
                         //由URL的openConnection方法得到一個HttpURLConnection(需要強轉)
                         HttpURLConnection httpURLConnection =
                                 (HttpURLConnection) url.openConnection();
                         //設置post提交
                         httpURLConnection.setRequestMethod("POST");
                         //設置超時時間
                         httpURLConnection.setConnectTimeout(30000);
                         httpURLConnection.setReadTimeout(30000);

                         httpURLConnection.setDoInput(true);
                       httpURLConnection.setDoOutput(true);

                         //把請求正文通過OutputStream發出去
                         OutputStream os =httpURLConnection.getOutputStream();
                         os.write(request.getBytes());
                         os.flush();

                         //判斷響應碼  200 代表成功
                         if(httpURLConnection.getResponseCode()==200){
                             //由HttpURLConnection拿到輸入流
                             InputStream in=httpURLConnection.getInputStream();
                             StringBuffer sb=new StringBuffer();
                             //根據輸入流做一些IO操作
                             byte [] buff =new byte[1024];
                             int len=-1;
                             while((len=in.read(buff))!=-1){
                                 sb.append(new String(buff,0,len,"utf-8"));
                             }

                             in.close();
                             os.close();
                             httpURLConnection.disconnect();
                             return  sb.toString();
                         }else{
                             return null;
                         }

                     }catch (Exception e){
                         Log.e("post","code:"+e.getMessage());
                         return null;
                     }
                 }
}

發佈了24 篇原創文章 · 獲贊 7 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章