Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1501183
  • 博文数量: 329
  • 博客积分: 2773
  • 博客等级: 少校
  • 技术积分: 4219
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-24 14:17
个人简介

淡定从容,宁静致远

文章分类

全部博文(329)

文章存档

2016年(4)

2015年(50)

2014年(68)

2013年(45)

2012年(162)

分类: Java

2015-11-25 16:19:18

public static String htttpRequest(String strURL, String params) {
try {   
            URL url = new URL(strURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
            connection.setDoOutput(true);   
            connection.setDoInput(true);   
            connection.setUseCaches(false);   
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST");//设定请求的方法为"POST",默认是GET
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();   
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            out.append(params);   
            out.flush();   
            out.close();   
            int length = (int) connection.getContentLength();
            InputStream is = connection.getInputStream();   
            if (length != -1) {   
                byte[] data = new byte[length];   
                byte[] temp = new byte[512];   
                int readLen = 0;   
                int destPos = 0;   
                while ((readLen = is.read(temp)) > 0) {   
                    System.arraycopy(temp, 0, data, destPos, readLen);   
                    destPos += readLen;   
                }   
                String result = new String(data, "UTF-8");
                //System.out.println(result);   
                return result;   
            }   
        } catch (IOException e) {   
            e.printStackTrace();   
        }   
        return "error";
}
阅读(1495) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~