Beispiel #1
0
 public void run() {
   try {
     Thread.sleep(10);
     byte[] buf = getBuf();
     URL url = new URL("http://127.0.0.1:" + port + "/test");
     HttpURLConnection con = (HttpURLConnection) url.openConnection();
     con.setDoOutput(true);
     con.setDoInput(true);
     con.setRequestMethod("POST");
     con.setRequestProperty(
         "Content-Type",
         "Multipart/Related; type=\"application/xop+xml\"; boundary=\"----=_Part_0_6251267.1128549570165\"; start-info=\"text/xml\"");
     OutputStream out = con.getOutputStream();
     out.write(buf);
     out.close();
     InputStream in = con.getInputStream();
     byte[] newBuf = readFully(in);
     in.close();
     if (buf.length != newBuf.length) {
       System.out.println("Doesn't match");
       error = true;
     }
     synchronized (lock) {
       ++received;
       if ((received % 1000) == 0) {
         System.out.println("Received=" + received);
       }
     }
   } catch (Exception e) {
     // e.printStackTrace();
     System.out.print(".");
     error = true;
   }
 }
  /**
   * Login with user name and password sent as String parameter to url using POST Interrogation
   *
   * @param username
   * @param userpass
   * @throws IOException
   */
  @And("^I make post message with user: \"([^\"]*)\" and password: \"([^\"]*)\"$")
  public void HttpPostForm(String username, String userpass) throws IOException {

    URL url = new URL("http://dippy.trei.ro");

    HttpURLConnection hConnection = (HttpURLConnection) url.openConnection();
    HttpURLConnection.setFollowRedirects(true);

    hConnection.setDoOutput(true);
    hConnection.setRequestMethod("POST");

    PrintStream ps = new PrintStream(hConnection.getOutputStream());
    ps.print("user="******"&pass="******";do_login=Login");
    ps.close();

    hConnection.connect();

    if (HttpURLConnection.HTTP_OK == hConnection.getResponseCode()) {
      InputStream is = hConnection.getInputStream();

      System.out.println("!!! encoding: " + hConnection.getContentEncoding());
      System.out.println("!!! message: " + hConnection.getResponseMessage());

      is.close();
      hConnection.disconnect();
    }
  }
Beispiel #3
0
 public void sendMessage(String message) {
   checkConnected();
   HttpURLConnection outcomeConnection = null;
   try {
     CLIENT_LOGGER.info("start sending message \"" + message + "\"");
     outcomeConnection = prepareOutputConnection();
     byte[] buffer = MessageHelper.buildSendMessageRequestBody(message).getBytes();
     OutputStream outputStream = outcomeConnection.getOutputStream();
     outputStream.write(buffer, 0, buffer.length);
     outputStream.close();
     outcomeConnection.getInputStream(); // to send data to server
     CLIENT_LOGGER.info("message sent");
   } catch (ConnectException e) {
     logger.error("Connection error. Disconnecting...", e);
     CLIENT_LOGGER.error("connection error", e);
     disconnect();
   } catch (IOException e) {
     CLIENT_LOGGER.error("IOException", e);
     logger.error("IOException occurred while sending message", e);
   } finally {
     if (outcomeConnection != null) {
       outcomeConnection.disconnect();
     }
     CLIENT_LOGGER.info("stop sending message \"" + message + "\"");
   }
 }
Beispiel #4
0
  /**
   * Method to update database on the server with new and changed hazards given as a JSONObject
   * instance
   *
   * @param uploadHazards A JSONObject instance with encoded new and update hazards
   * @throws IOException
   */
  public static void uploadHazards(JSONObject uploadHazards) throws IOException {
    // upload hazards in json to php (to use json_decode)
    // Hazard parameter should be encoded as json already

    // Set Post connection
    URL url = new URL(site + "/update.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setRequestMethod("POST");

    OutputStream writer = conn.getOutputStream();
    writer.write(
        uploadHazards.toString().getBytes("UTF-8")); // toString produces compact JSONString
    // no white space
    writer.close();
    // read response (success / error)

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer response = new StringBuffer();
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
    }
    in.close();
  }
Beispiel #5
0
  /**
   * Method to return a set of hazard data within CACHE_DISTANCE of given location
   *
   * @param location An instance of Location that stores latitude and longitude data
   * @return JSONObject an instance of JSONObject with json encoded hazard data
   * @throws IOException
   * @throws JSONException
   */
  public static JSONObject getHazards(LatLng location) throws IOException, JSONException {
    // request hazards from long / lat data and retrieve json hazards
    // tested and working!

    String longitude = String.valueOf(location.longitude);
    String latitude = String.valueOf(location.latitude);

    String query = String.format("longitude=%s&latitude=%s", longitude, latitude);
    // encode the post query

    // Set a POST connection
    URL url = new URL(site + "/request.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    System.out.println(query);
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setDoInput(true);

    // Send post request
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(query);
    writer.flush();
    writer.close();

    BufferedReader response = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer hazards = new StringBuffer();
    String inputLine;
    while ((inputLine = response.readLine()) != null) {
      hazards.append(inputLine);
    }

    response.close();

    return new JSONObject(hazards.toString());
  }
 private int send(final String yaml, final HttpURLConnection connection) throws IOException {
   int statusCode;
   final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
   writer.write(yaml);
   writer.close();
   statusCode = connection.getResponseCode();
   return statusCode;
 }
Beispiel #7
0
  /**
   * 请求xml数据
   *
   * @param url
   * @param soapAction
   * @param xml
   * @return
   */
  public static String sendXMl(String url, String soapAction, String xml) {
    HttpURLConnection conn = null;
    InputStream in = null;
    InputStreamReader isr = null;
    OutputStream out = null;
    StringBuffer result = null;
    try {
      byte[] sendbyte = xml.getBytes("UTF-8");
      URL u = new URL(url);
      conn = (HttpURLConnection) u.openConnection();
      conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
      conn.setRequestProperty("SOAPAction", soapAction);
      conn.setRequestProperty("Content-Length", sendbyte.length + "");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setConnectTimeout(5000);
      conn.setReadTimeout(5000);

      out = conn.getOutputStream();
      out.write(sendbyte);

      if (conn.getResponseCode() == 200) {
        result = new StringBuffer();
        in = conn.getInputStream();
        isr = new InputStreamReader(in, "UTF-8");
        char[] c = new char[1024];
        int a = isr.read(c);
        while (a != -1) {
          result.append(new String(c, 0, a));
          a = isr.read(c);
        }
      }

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (conn != null) {
        conn.disconnect();
      }
      try {
        if (in != null) {
          in.close();
        }
        if (isr != null) {
          isr.close();
        }
        if (out != null) {
          out.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return result == null ? null : result + "";
  }
Beispiel #8
0
  private String postResult(String URL) {
    StringBuffer sb = new StringBuffer();
    try {

      String finalUrl = "";

      String[] parsedUrl = URL.split("\\?");
      String params =
          URLEncoder.encode(parsedUrl[1], "UTF-8").replace("%3D", "=").replace("%26", "&");

      URL url = new URL(parsedUrl[0] + "?" + params);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());

      conn.setDoOutput(true);
      DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
      wr.writeBytes(params);
      wr.flush();
      wr.close();

      boolean redirect = false;
      // normally, 3xx is redirect
      int status = conn.getResponseCode();
      if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP
            || status == HttpURLConnection.HTTP_MOVED_PERM
            || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true;
      }

      if (redirect) {

        // get redirect url from "location" header field
        String newUrl = conn.getHeaderField("Location");

        // open the new connnection again
        conn = (HttpURLConnection) new URL(newUrl).openConnection();
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      }

      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String inputLine;

      while ((inputLine = in.readLine()) != null) {
        sb.append(inputLine);
      }
      in.close();

    } catch (Exception e) {
      e.printStackTrace();
    }

    return sb.toString();
  }
Beispiel #9
0
  void addBody(HttpURLConnection conn, byte[] content) throws IOException {
    conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(content.length));

    // Set default content type if none is set.
    if (conn.getRequestProperty(CONTENT_TYPE) == null) {
      conn.setRequestProperty(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
    }
    conn.setDoOutput(true);
    conn.getOutputStream().write(content);
  }
Beispiel #10
0
  private static NameValuePair<Long> poll(Config.HostInfo host, long minAge) throws IOException {

    NameValuePair<Long> run = null;
    URL target = new URL(host.url, SERVLET_PATH);

    HttpURLConnection c;
    if (host.proxyHost != null)
      c =
          (HttpURLConnection)
              target.openConnection(
                  new Proxy(
                      Proxy.Type.HTTP, new InetSocketAddress(host.proxyHost, host.proxyPort)));
    else c = (HttpURLConnection) target.openConnection();

    try {
      c.setRequestMethod("POST");
      c.setConnectTimeout(2000);
      c.setDoOutput(true);
      c.setDoInput(true);
      PrintWriter out = new PrintWriter(c.getOutputStream());
      out.write("host=" + Config.FABAN_HOST + "&key=" + host.key + "&minage=" + minAge);
      out.flush();
      out.close();
    } catch (SocketTimeoutException e) {
      logger.log(Level.WARNING, "Timeout trying to connect to " + target + '.', e);
      throw new IOException("Socket connect timeout");
    }

    int responseCode = c.getResponseCode();

    if (responseCode == HttpServletResponse.SC_OK) {
      InputStream is = c.getInputStream();

      // The input is a one liner in the form runId\tAge
      byte[] buffer = new byte[256]; // Very little cost for this new/GC.
      int size = is.read(buffer);

      // We have to close the input stream in order to return it to
      // the cache, so we get it for all content, even if we don't
      // use it. It's (I believe) a bug that the content handlers used
      // by getContent() don't close the input stream, but the JDK team
      // has marked those bugs as "will not fix."
      is.close();

      StringTokenizer t = new StringTokenizer(new String(buffer, 0, size), "\t\n");
      run = new NameValuePair<Long>();
      run.name = t.nextToken();
      run.value = Long.parseLong(t.nextToken());
    } else if (responseCode != HttpServletResponse.SC_NO_CONTENT) {
      logger.warning("Polling " + target + " got response code " + responseCode);
    }
    return run;
  }
    private String transportHttpMessage(String message) {
      URL serverurl;
      HttpURLConnection connection;

      try {
        serverurl = new URL(this.ServerUrl);
        connection = (HttpURLConnection) serverurl.openConnection();
        connection.setDefaultUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }

      OutputStreamWriter outstream;
      try {
        outstream = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        outstream.write(message);
        outstream.flush();
        /*
        PrintWriter writer = new PrintWriter(outstream);
        writer.write(message);
        writer.flush();
        */
        outstream.close();
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }

      StringBuilder strbuilder = new StringBuilder();
      try {
        InputStreamReader instream = new InputStreamReader(connection.getInputStream(), "UTF-8");
        BufferedReader reader = new BufferedReader(instream);

        String str;
        while ((str = reader.readLine()) != null) strbuilder.append(str + "\r\n");

        instream.close();
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }

      connection.disconnect();
      return strbuilder.toString();
    }
  @Override
  protected TicketItemResponse doInBackground(String... urls) {

    TicketItemResponse result = null;

    String uri = GV.URL + "/AddMenuItemToTicketServlet";

    try {

      URL url = new URL(uri);
      CookieManager cookieManager = new CookieManager();
      CookieHandler.setDefault(cookieManager);

      HttpURLConnection connection = (HttpURLConnection) url.openConnection();

      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("ticketId", String.valueOf(ticketId)));
      params.add(new BasicNameValuePair("menuItemId", String.valueOf(menuItemId)));
      params.add(new BasicNameValuePair("userId", String.valueOf(userId)));
      connection.setRequestMethod("POST");
      connection.setDoInput(true);
      connection.setDoOutput(true);

      OutputStream os = connection.getOutputStream();
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
      writer.write(getQuery(params));
      writer.flush();
      writer.close();
      os.close();

      BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

      StringBuilder temp = new StringBuilder();
      String inputLine;

      while ((inputLine = in.readLine()) != null) {
        temp.append((inputLine));
      }

      in.close();

      result = new Gson().fromJson(temp.toString(), TicketItemResponse.class);

    } catch (Exception e) {
      e.printStackTrace();
    }

    return result;
  }
  // добавить продукт в базу json server
  public static void add(ProductREST product) throws NotValidProductException, IOException {
    try {
      check(product); // рповеряем продукт
      // connection к серверу
      HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection()));
      con.setRequestMethod("POST"); // метод post для добавления

      // генерируем запрос
      StringBuilder urlParameters = new StringBuilder();
      urlParameters
          .append("name=")
          .append(URLEncoder.encode(product.getName(), "UTF8"))
          .append("&");
      urlParameters.append("price=").append(product.getPrice()).append("&");
      urlParameters.append("weight=").append(product.getWeight()).append("&");
      urlParameters
          .append("manufacturer=")
          .append(product.getManufacturer().getCountry())
          .append("&");
      urlParameters.append("category=").append(URLEncoder.encode(product.getCategory(), "UTF8"));

      con.setDoOutput(true); // разрешаем отправку данных
      // отправляем
      try (DataOutputStream out = new DataOutputStream(con.getOutputStream())) {
        out.writeBytes(urlParameters.toString());
      }
      // код ответа
      int responseCode = con.getResponseCode();
      System.out.println("\nSending 'POST' request to URL : " + PRODUCT_URL);
      System.out.println("Response Code : " + responseCode);

    } catch (NotValidProductException e) {
      e.printStackTrace();
      throw e;
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      throw new UnsupportedEncodingException("cannot recognize encoding");
    } catch (ProtocolException e) {
      e.printStackTrace();
      throw new ProtocolException("No such protocol, protocol must be POST,DELETE,PATCH,GET etc.");
    } catch (MalformedURLException e) {
      e.printStackTrace();
      throw new MalformedURLException("Url is not valid");
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException("cannot write information to server");
    }
  }
Beispiel #14
0
  /**
   * 通过post方式访问短信接口
   *
   * @param param sms message, like key1=value1&key2=value2
   * @param isproxy 是否启用代理模式
   * @return
   */
  public String sendPost(String param, boolean isproxy) {
    OutputStreamWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
      URL realUrl = new URL(this.url);
      HttpURLConnection conn = null;

      conn = (HttpURLConnection) realUrl.openConnection();

      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.setRequestMethod("POST"); // POST方法

      conn.setRequestProperty("accept", "*/*");
      conn.setRequestProperty("connection", "Keep-Alive");
      conn.setRequestProperty(
          "user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      conn.connect();

      out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
      out.write(param);
      out.flush();
      in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        result += line;
      }
    } catch (Exception e) {
      System.out.println("[ERROR]发送 POST 请求出现异常!" + e);
      e.printStackTrace();
    } finally {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    return result;
  }
Beispiel #15
0
  private static File download(Config.HostInfo host, NameValuePair<Long> run) throws IOException {

    File jarFile = null;
    FileOutputStream jarOut = null;
    URL target = new URL(host.url, SERVLET_PATH);

    HttpURLConnection c = null;
    try {
      c = (HttpURLConnection) target.openConnection();
      c.setRequestMethod("POST");
      c.setConnectTimeout(2000);
      c.setDoOutput(true);
      c.setDoInput(true);
      PrintWriter out = new PrintWriter(c.getOutputStream());
      out.write("host=" + Config.FABAN_HOST + "&key=" + host.key + "&runid=" + run.name);
      out.flush();
      out.close();
    } catch (SocketTimeoutException e) {
      logger.log(Level.WARNING, "Timeout trying to connect to " + target + '.', e);
      throw new IOException("Socket connect timeout");
    }

    int responseCode = c.getResponseCode();
    if (responseCode == HttpServletResponse.SC_OK) {
      InputStream is = c.getInputStream();
      // We allocate in every method instead of a central buffer
      // to allow concurrent downloads. This can be expanded to use
      // buffer pools to avoid GC, if necessary.
      byte[] buffer = new byte[8192];
      int size;
      while ((size = is.read(buffer)) != -1) {
        if (size > 0 && jarFile == null) {
          jarFile = new File(Config.TMP_DIR, host.name + '.' + run.name + ".jar");
          jarOut = new FileOutputStream(jarFile);
        }
        jarOut.write(buffer, 0, size);
      }
      is.close();
      jarOut.flush();
      jarOut.close();
    } else {
      logger.warning(
          "Downloading run " + run.name + " from " + target + " got response code " + responseCode);
    }
    return jarFile;
  }
Beispiel #16
0
  public String performPostCall(String requestURL, String param) {

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

    StrictMode.setThreadPolicy(policy);

    URL url;
    String response = "";
    try {
      url = new URL(requestURL);

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(15000);
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("POST");
      conn.setDoInput(true);
      conn.setDoOutput(true);

      OutputStream os = conn.getOutputStream();
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
      writer.write(param);

      writer.flush();
      writer.close();
      os.close();
      // int responseCode=conn.getResponseCode();

      // if (responseCode == HttpURLConnection.HTTP_OK) {
      String line;
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      while ((line = br.readLine()) != null) {
        response += line;
      }
      //  }
      //  else {
      //  response= null;

      //  }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return response;
  }
Beispiel #17
0
    @Override
    public HTTPResponse call() throws Exception {
      final HttpURLConnection hc = (HttpURLConnection) uri.toURL().openConnection();
      try {
        hc.setDoOutput(true);
        hc.setRequestMethod(method.name());
        hc.setRequestProperty(MimeTypes.CONTENT_TYPE, MimeTypes.APP_XML);
        hc.getOutputStream().write(content);
        hc.getOutputStream().close();

        hc.setReadTimeout(SOCKET_TIMEOUT);
        while (!stop) {
          try {
            return new HTTPResponse(hc.getResponseCode());
          } catch (final SocketTimeoutException e) {
          }
        }
        return null;
      } finally {
        hc.disconnect();
      }
    }
    protected Void doInBackground(Void... params) {
      String outString;
      HttpURLConnection c = null;
      DataOutputStream os = null;

      outString = scanData.getOwnBSSID();
      outString = outString + "\nL\tX\t" + lastLat + "\t" + lastLon + "\n";

      try {
        URL connectURL = new URL("http://www.openwlanmap.org/android/upload.php");
        c = (HttpURLConnection) connectURL.openConnection();
        if (c == null) {
          return null;
        }

        c.setDoOutput(true); // enable POST
        c.setRequestMethod("POST");
        c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded, *.*");
        c.addRequestProperty("Content-Length", "" + outString.length());
        os = new DataOutputStream(c.getOutputStream());
        os.write(outString.getBytes());
        os.flush();
        c.getResponseCode();
        os.close();
        outString = null;
        os = null;
      } catch (IOException ioe) {
      } finally {
        try {
          if (os != null) os.close();
          if (c != null) c.disconnect();
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }
      }
      return null;
    }
Beispiel #19
0
  /**
   * When you call this, you post the data, after which it is gone. The post is synchronous. The
   * function returns after posting and receiving a reply. Get a new data stream with
   * startDataStream() to make a new post. (You could hold on to the writer, but using it will have
   * no effect after calling this method.)
   *
   * @return HTTP response code, 200 means successful.
   */
  public int postToCDB() throws IOException, ProtocolException, UnsupportedEncodingException {
    cdbId = -1;
    if (dataWriter == null) {
      throw new IllegalStateException("call startDataStream() and write something first");
    }
    HttpURLConnection connection = (HttpURLConnection) postURL.openConnection();
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    dataWriter.flush();
    String data = JASPER_DATA_PARAM + "=" + URLEncoder.encode(dataWriter.toString(), "UTF-8");
    dataWriter = null;

    connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.writeBytes(data);
    out.flush();
    out.close();

    int responseCode = connection.getResponseCode();
    wasSuccessful = (200 == responseCode);
    InputStream response;
    if (wasSuccessful) {
      response = connection.getInputStream();
    } else {
      response = connection.getErrorStream();
    }
    if (response != null) processResponse(response);
    connection.disconnect();

    return responseCode;
  }
Beispiel #20
0
  public static String httpPost(String urlAddress, String[] params) {
    URL url = null;
    HttpURLConnection conn = null;
    BufferedReader in = null;
    StringBuffer sb = new StringBuffer();

    try {
      url = new URL(urlAddress);
      conn = (HttpURLConnection) url.openConnection(); // 建立连接
      // 设置通用的请求属性
      /*
       * conn.setRequestProperty("user-agent",
       * "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
       */
      conn.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
      conn.setRequestProperty("Accept", "*/*");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      conn.setUseCaches(false);
      conn.setDoInput(true);
      // conn.setConnectTimeout(5 * 1000);
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      String paramsTemp = "";
      for (String param : params) {
        if (param != null && !"".equals(param)) {
          if (params.length > 1) {
            paramsTemp += "&" + param;
          } else if (params.length == 1) {
            paramsTemp = params[0];
          }
        }
      }

      byte[] b = paramsTemp.getBytes();
      System.out.println("btye length:" + b.length);
      // conn.setRequestProperty("Content-Length",
      // String.valueOf(b.length));
      conn.getOutputStream().write(b, 0, b.length);
      conn.getOutputStream().flush();
      conn.getOutputStream().close();
      int count = conn.getResponseCode();
      if (200 == count) {
        in = new BufferedReader(new InputStreamReader(conn.getInputStream())); // 发送请求
      } else {
        System.out.println("错误类型:" + count);
        return "server no start-up";
      }

      while (true) {
        String line = in.readLine();
        if (line == null) {
          break;
        } else {
          sb.append(line);
        }
      }
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("error ioexception:" + e.getMessage());
      e.printStackTrace();
      return "server no start-up";
    } finally {
      try {
        if (in != null) {
          in.close();
        }
        if (conn != null) {
          conn.disconnect();
        }
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return sb.toString();
  }
Beispiel #21
0
  /**
   * 登陆百度,其他方法调用之前需要先登陆
   *
   * @param username
   * @param password
   */
  public void login(String username, String password) {
    try {
      URL url = new URL("http://www.baidu.com/");
      HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
      httpUrlConnection.setRequestMethod("GET");
      String cookie1 = httpUrlConnection.getHeaderField("Set-Cookie");
      // System.out.println("cookie1:"+cookie1);
      cookie1 = cookie1.substring(0, 45);

      url = new URL("https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true");
      httpUrlConnection = (HttpURLConnection) url.openConnection();
      httpUrlConnection.setRequestMethod("GET");
      httpUrlConnection.setRequestProperty("Cookie", cookie1);
      // httpUrlConnection.connect();
      String cookie2 = httpUrlConnection.getHeaderField("Set-Cookie");
      System.out.println("cookie2:" + cookie2);
      cookie2 = cookie2.substring(0, 11);
      String response = getResponse(httpUrlConnection.getInputStream());
      // System.out.println(response);
      Pattern pattern = Pattern.compile("token='(\\w+)'");
      Matcher matcher = pattern.matcher(response);
      matcher.find();
      String token = matcher.group(1);

      url = new URL("https://passport.baidu.com/v2/api/?login");
      httpUrlConnection = (HttpURLConnection) url.openConnection();
      httpUrlConnection.setRequestMethod("POST");
      // System.out.println(cookie1+"; "+cookie2);
      httpUrlConnection.setRequestProperty("Cookie", cookie1 + "; " + cookie2);
      httpUrlConnection.setDoOutput(true);
      // System.out.println(token);

      String querystring =
          "loginType=1&tpl=mn&token="
              + token
              + "&username="******"&password="******"&mem_pass=on";
      httpUrlConnection.getOutputStream().write(querystring.getBytes());
      httpUrlConnection.getOutputStream().flush();
      httpUrlConnection.getOutputStream().close();

      response = getResponse(httpUrlConnection.getInputStream());
      // System.out.println(response);

      // String cookie3=httpUrlConnection.getHeaderField("Set-Cookie");
      // System.out.println("cookie3:"+cookie3);

      // 获取登陆后的cookie
      Map<String, List<String>> hfs = httpUrlConnection.getHeaderFields();
      List<String> loginCookies = hfs.get("Set-Cookie");
      for (String cookie : loginCookies) {
        cookieValue += cookie.substring(0, cookie.indexOf(";") + 1);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 /**
  * This calls the external Moodle web service.
  *
  * <p>params String containing the parameters of the call.<br>
  * elements NodeList containing name/value pairs of returned XML data.
  *
  * @param params String
  * @return elements NodeList
  * @throws MoodleRestException
  */
 public static NodeList call(String params) throws MoodleRestException {
   NodeList elements = null;
   try {
     URL getUrl = new URL(url);
     HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
     connection.setRequestMethod("POST");
     connection.setRequestProperty("Accept", "application/xml");
     connection.setDoOutput(true);
     OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
     writer.write(params);
     writer.flush();
     writer.close();
     // Used for testing
     StringBuilder buffer = new StringBuilder();
     BufferedReader reader =
         new BufferedReader(new InputStreamReader(connection.getInputStream()));
     String line = reader.readLine();
     buffer.append(line).append('\n');
     // FindPath fp=new FindPath();
     InputStream resource =
         ClassLoader.getSystemClassLoader()
             .getResourceAsStream("net/beaconhillcott/moodlerest/EntityInjection.xml");
     BufferedReader entities = new BufferedReader(new InputStreamReader(/*fp.*/ resource));
     String entitiesLine = null;
     while ((entitiesLine = entities.readLine()) != null) {
       // System.out.println(entitiesLine);
       buffer.append(entitiesLine).append('\n');
     }
     entities.close();
     boolean error = false;
     while ((line = reader.readLine()) != null) {
       // System.out.println(line);
       if (error)
         throw new MoodleRestException(
             line.substring(line.indexOf('>') + 1, line.indexOf('<', line.indexOf('>') + 1)));
       if (line.contains("<EXCEPTION")) error = true;
       buffer.append(line).append('\n');
     }
     reader.close();
     if (debug) {
       System.out.println(buffer.toString());
     }
     XPath xpath = XPathFactory.newInstance().newXPath();
     // InputSource source=new InputSource(connection.getInputStream());
     InputSource source = new InputSource(new ByteArrayInputStream(buffer.toString().getBytes()));
     elements = (NodeList) xpath.evaluate("//VALUE", source, XPathConstants.NODESET);
     // Used for testing
     if (debug) {
       for (int i = 0; i < elements.getLength(); i++) {
         String parent =
             elements
                 .item(i)
                 .getParentNode()
                 .getParentNode()
                 .getParentNode()
                 .getParentNode()
                 .getNodeName();
         if (parent.equals("KEY"))
           parent =
               elements
                   .item(i)
                   .getParentNode()
                   .getParentNode()
                   .getParentNode()
                   .getParentNode()
                   .getAttributes()
                   .getNamedItem("name")
                   .getNodeValue();
         String content = elements.item(i).getTextContent();
         String nodeName =
             elements.item(i).getParentNode().getAttributes().getNamedItem("name").getNodeValue();
         System.out.println("parent=" + parent + " nodeName=" + nodeName + " content=" + content);
       }
     }
     connection.disconnect();
   } catch (XPathExpressionException ex) {
     Logger.getLogger(MoodleCallRestWebService.class.getName()).log(Level.SEVERE, null, ex);
   } catch (IOException ex) {
     Logger.getLogger(MoodleCallRestWebService.class.getName()).log(Level.SEVERE, null, ex);
   }
   return elements;
 }
  SOAPMessage post(SOAPMessage message, URL endPoint) throws SOAPException {
    boolean isFailure = false;

    URL url = null;
    HttpURLConnection httpConnection = null;

    int responseCode = 0;
    try {
      if (endPoint.getProtocol().equals("https"))
        // if(!setHttps)
        initHttps();
      // Process the URL
      JaxmURI uri = new JaxmURI(endPoint.toString());
      String userInfo = uri.getUserinfo();

      url = endPoint;

      if (dL > 0) d("uri: " + userInfo + " " + url + " " + uri);

      // TBD
      //    Will deal with https later.
      if (!url.getProtocol().equalsIgnoreCase("http")
          && !url.getProtocol().equalsIgnoreCase("https")) {
        log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https");
        throw new IllegalArgumentException(
            "Protocol " + url.getProtocol() + " not supported in URL " + url);
      }
      httpConnection = (HttpURLConnection) createConnection(url);

      httpConnection.setRequestMethod("POST");

      httpConnection.setDoOutput(true);
      httpConnection.setDoInput(true);
      httpConnection.setUseCaches(false);
      httpConnection.setInstanceFollowRedirects(true);

      if (message.saveRequired()) message.saveChanges();

      MimeHeaders headers = message.getMimeHeaders();

      Iterator it = headers.getAllHeaders();
      boolean hasAuth = false; // true if we find explicit Auth header
      while (it.hasNext()) {
        MimeHeader header = (MimeHeader) it.next();

        String[] values = headers.getHeader(header.getName());
        if (values.length == 1)
          httpConnection.setRequestProperty(header.getName(), header.getValue());
        else {
          StringBuffer concat = new StringBuffer();
          int i = 0;
          while (i < values.length) {
            if (i != 0) concat.append(',');
            concat.append(values[i]);
            i++;
          }

          httpConnection.setRequestProperty(header.getName(), concat.toString());
        }

        if ("Authorization".equals(header.getName())) {
          hasAuth = true;
          log.fine("SAAJ0091.p2p.https.auth.in.POST.true");
        }
      }

      if (!hasAuth && userInfo != null) {
        initAuthUserInfo(httpConnection, userInfo);
      }

      OutputStream out = httpConnection.getOutputStream();
      message.writeTo(out);

      out.flush();
      out.close();

      httpConnection.connect();

      try {

        responseCode = httpConnection.getResponseCode();

        // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        }
        // else if (responseCode != HttpURLConnection.HTTP_OK)
        // else if (!(responseCode >= HttpURLConnection.HTTP_OK && responseCode < 207))
        else if ((responseCode / 100) != 2) {
          log.log(
              Level.SEVERE,
              "SAAJ0008.p2p.bad.response",
              new String[] {httpConnection.getResponseMessage()});
          throw new SOAPExceptionImpl(
              "Bad response: (" + responseCode + httpConnection.getResponseMessage());
        }
      } catch (IOException e) {
        // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds!
        responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
          isFailure = true;
        } else {
          throw e;
        }
      }

    } catch (SOAPException ex) {
      throw ex;
    } catch (Exception ex) {
      log.severe("SAAJ0009.p2p.msg.send.failed");
      throw new SOAPExceptionImpl("Message send failed", ex);
    }

    SOAPMessage response = null;
    if (responseCode == HttpURLConnection.HTTP_OK || isFailure) {
      try {
        MimeHeaders headers = new MimeHeaders();

        String key, value;

        // Header field 0 is the status line so we skip it.

        int i = 1;

        while (true) {
          key = httpConnection.getHeaderFieldKey(i);
          value = httpConnection.getHeaderField(i);

          if (key == null && value == null) break;

          if (key != null) {
            StringTokenizer values = new StringTokenizer(value, ",");
            while (values.hasMoreTokens()) headers.addHeader(key, values.nextToken().trim());
          }
          i++;
        }

        InputStream httpIn =
            (isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream());

        byte[] bytes = readFully(httpIn);

        int length =
            httpConnection.getContentLength() == -1
                ? bytes.length
                : httpConnection.getContentLength();

        // If no reply message is returned,
        // content-Length header field value is expected to be zero.
        if (length == 0) {
          response = null;
          log.warning("SAAJ0014.p2p.content.zero");
        } else {
          ByteInputStream in = new ByteInputStream(bytes, length);
          response = messageFactory.createMessage(headers, in);
        }

        httpIn.close();
        httpConnection.disconnect();

      } catch (SOAPException ex) {
        throw ex;
      } catch (Exception ex) {
        log.log(Level.SEVERE, "SAAJ0010.p2p.cannot.read.resp", ex);
        throw new SOAPExceptionImpl("Unable to read response: " + ex.getMessage());
      }
    }
    return response;
  }
  public InputStream upload() throws ResourceUploaderException {

    try {

      try {
        URL url = new URL(target.toString().replaceAll(" ", "%20"));

        // some authentications screw up without an explicit port number here

        String protocol = url.getProtocol().toLowerCase();

        if (url.getPort() == -1) {

          int target_port;

          if (protocol.equals("http")) {

            target_port = 80;

          } else {

            target_port = 443;
          }

          try {
            String str = target.toString().replaceAll(" ", "%20");

            int pos = str.indexOf("://");

            pos = str.indexOf("/", pos + 4);

            // might not have a trailing "/"

            if (pos == -1) {

              url = new URL(str + ":" + target_port + "/");

            } else {

              url = new URL(str.substring(0, pos) + ":" + target_port + str.substring(pos));
            }

          } catch (Throwable e) {

            Debug.printStackTrace(e);
          }
        }

        url = AddressUtils.adjustURL(url);

        try {
          if (user_name != null) {

            SESecurityManager.setPasswordHandler(url, this);
          }

          for (int i = 0; i < 2; i++) {

            try {
              HttpURLConnection con;

              if (url.getProtocol().equalsIgnoreCase("https")) {

                // see ConfigurationChecker for SSL client defaults

                HttpsURLConnection ssl_con = (HttpsURLConnection) url.openConnection();

                // allow for certs that contain IP addresses rather than dns names

                ssl_con.setHostnameVerifier(
                    new HostnameVerifier() {
                      public boolean verify(String host, SSLSession session) {
                        return (true);
                      }
                    });

                con = ssl_con;

              } else {

                con = (HttpURLConnection) url.openConnection();
              }

              con.setRequestMethod("POST");

              con.setRequestProperty(
                  "User-Agent", Constants.AZUREUS_NAME + " " + Constants.AZUREUS_VERSION);

              con.setDoOutput(true);
              con.setDoInput(true);

              OutputStream os = con.getOutputStream();

              byte[] buffer = new byte[65536];

              while (true) {

                int len = data.read(buffer);

                if (len <= 0) {

                  break;
                }

                os.write(buffer, 0, len);
              }

              con.connect();

              int response = con.getResponseCode();

              if ((response != HttpURLConnection.HTTP_ACCEPTED)
                  && (response != HttpURLConnection.HTTP_OK)) {

                throw (new ResourceUploaderException(
                    "Error on connect for '"
                        + url.toString()
                        + "': "
                        + Integer.toString(response)
                        + " "
                        + con.getResponseMessage()));
              }

              return (con.getInputStream());

            } catch (SSLException e) {

              if (i == 0) {

                if (SESecurityManager.installServerCertificates(url) != null) {

                  // certificate has been installed

                  continue; // retry with new certificate
                }
              }

              throw (e);
            }
          }

          throw (new ResourceUploaderException("Should never get here"));

        } finally {

          if (user_name != null) {

            SESecurityManager.setPasswordHandler(url, null);
          }
        }
      } catch (java.net.MalformedURLException e) {

        throw (new ResourceUploaderException(
            "Exception while parsing URL '" + target + "':" + e.getMessage(), e));

      } catch (java.net.UnknownHostException e) {

        throw (new ResourceUploaderException(
            "Exception while initializing download of '"
                + target
                + "': Unknown Host '"
                + e.getMessage()
                + "'",
            e));

      } catch (java.io.IOException e) {

        throw (new ResourceUploaderException(
            "I/O Exception while downloading '" + target + "':" + e.toString(), e));
      }
    } catch (Throwable e) {

      ResourceUploaderException rde;

      if (e instanceof ResourceUploaderException) {

        rde = (ResourceUploaderException) e;

      } else {

        rde = new ResourceUploaderException("Unexpected error", e);
      }

      throw (rde);

    } finally {

      try {
        data.close();

      } catch (Throwable e) {

        e.printStackTrace();
      }
    }
  }