HttpURLConnection post请求 数据接收

String urlPath = new String("http://127.0.0.1:8080/MCServer/mobilesx.do??token=1475197252625&filename=2202&trancode=MCMENUSX000000013&action=mcrm&usrno=BWZY");
    
    //建立连接
    URL url=new URL(urlPath);
    HttpURLConnection httpConn=(HttpURLConnection)url.openConnection();
    //设置参数
    httpConn.setDoOutput(true);   //需要输出
    httpConn.setDoInput(true);   //需要输入
    httpConn.setUseCaches(false);  //不允许缓存
    httpConn.setRequestMethod("POST");   //设置POST方式连接
    //设置请求属性"Content-Type"是数据类型 "application/octet-stream"
//    httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//文本信息
    httpConn.setRequestProperty("Content-Type", "application/octet-stream");//流信息 可以传输图片音频等信息
    httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
    httpConn.setRequestProperty("Charset", "UTF-8");
    //连接,也可以不用明文connect,使用下面的httpConn.getOutputStream()会自动connect
    httpConn.connect();
    //建立输入流,向指向的URL传入参数
//    DataOutputStream dos=new DataOutputStream(httpConn.getOutputStream());
    OutputStream dos = httpConn.getOutputStream();
//    dos.write(param.getBytes());
    FileInputStream fis = new FileInputStream("E:/upload2/2202");
    byte[] b =new byte[fis.available()];
    fis.read(b);
    dos.write(b);
    dos.flush();
    dos.close();
    //获得响应状态
    int resultCode=httpConn.getResponseCode();
    if(HttpURLConnection.HTTP_OK==resultCode){
      StringBuffer sb=new StringBuffer();
      String readLine=new String();
      BufferedReader responseReader=new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
      while((readLine=responseReader.readLine())!=null){
        sb.append(readLine).append("\n");
      }
      responseReader.close();
      System.out.println(sb.toString());
    }
  }

posted @ 2016-09-30 10:19  精灵壶  阅读(9614)  评论(1编辑  收藏  举报