@Override
 public void close() throws IOException {
   try {
     if (urlConnection != null) {
       int responseCode = urlConnection.getResponseCode();
       if (responseCode != expectedResponseCode) {
         try {
           urlConnection.getInputStream().close();
           throw new IOException(
               String.format(
                   "Expected response code: %d. Got: %d", expectedResponseCode, responseCode));
         } catch (IOException expected) {
           InputStream errorStream = urlConnection.getErrorStream();
           if (errorStream != null) {
             String responseBody = FixJava.readReader(new InputStreamReader(errorStream, "UTF-8"));
             String contentType = urlConnection.getHeaderField("Content-Type");
             if (contentType == null) {
               contentType = "text/plain";
             }
             throw new ResponseException(responseBody, expected, responseCode, contentType);
           } else {
             throw expected;
           }
         }
       }
     }
   } finally {
     out.close();
   }
 }
Exemple #2
0
  /* (non-Javadoc)
   * @see com.googlecode.flickrjandroid.Transport#sendUpload(java.lang.String, java.util.List)
   */
  @Override
  protected Response sendUpload(String path, List<Parameter> parameters)
      throws IOException, FlickrException, SAXException {

    HttpURLConnection conn = null;
    DataOutputStream out = null;
    String data = null;
    try {
      URL url = UrlUtilities.buildPostUrl(getHost(), getPort(), path);

      conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("POST");
      String boundary = "---------------------------7d273f7a0d3";
      conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
      conn.setRequestProperty("Host", "api.flickr.com");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.connect();
      out = new DataOutputStream(conn.getOutputStream());
      boundary = "--" + boundary;
      out.writeBytes(boundary);
      Iterator<?> iter = parameters.iterator();
      while (iter.hasNext()) {
        Parameter p = (Parameter) iter.next();
        writeParam(p, out, boundary);
      }
      out.writeBytes("--\r\n\r\n");
      out.flush();
      out.close();

      int responseCode = HttpURLConnection.HTTP_OK;
      try {
        responseCode = conn.getResponseCode();
      } catch (IOException e) {
        // logger.error("Failed to get the POST response code", e);
        if (conn.getErrorStream() != null) {
          responseCode = conn.getResponseCode();
        }
      }
      if ((responseCode != HttpURLConnection.HTTP_OK)) {
        String errorMessage = readFromStream(conn.getErrorStream());
        throw new IOException(
            "Connection Failed. Response Code: "
                + responseCode
                + ", Response Message: "
                + conn.getResponseMessage()
                + ", Error: "
                + errorMessage);
      }
      UploaderResponse response = new UploaderResponse();
      Document document = builder.parse(conn.getInputStream());
      response.parse(document);
      return response;
    } finally {
      IOUtilities.close(out);
      if (conn != null) conn.disconnect();
    }
  }
Exemple #3
0
  public String sendPost(String path, List<Parameter> parameters) throws IOException {

    HttpURLConnection conn = null;
    DataOutputStream out = null;
    String data = null;
    try {
      URL url = UrlUtilities.buildPostUrl(getHost(), getPort(), path);

      conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("POST");
      String postParam = encodeParameters(parameters);
      byte[] bytes = postParam.getBytes(UTF8);
      conn.setRequestProperty("Content-Length", Integer.toString(bytes.length));
      conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      conn.addRequestProperty("Cache-Control", "no-cache,max-age=0");
      conn.addRequestProperty("Pragma", "no-cache");
      conn.setUseCaches(false);
      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.connect();
      out = new DataOutputStream(conn.getOutputStream());
      out.write(bytes);
      out.flush();
      out.close();

      int responseCode = HttpURLConnection.HTTP_OK;
      try {
        responseCode = conn.getResponseCode();
      } catch (IOException e) {
        // logger.error("Failed to get the POST response code", e);
        if (conn.getErrorStream() != null) {
          responseCode = conn.getResponseCode();
        }
      }
      if ((responseCode != HttpURLConnection.HTTP_OK)) {
        String errorMessage = readFromStream(conn.getErrorStream());
        throw new IOException(
            "Connection Failed. Response Code: "
                + responseCode
                + ", Response Message: "
                + conn.getResponseMessage()
                + ", Error: "
                + errorMessage);
      }

      String result = readFromStream(conn.getInputStream());
      data = result.trim();
      return data;
    } finally {
      IOUtilities.close(out);
      if (conn != null) conn.disconnect();
    }
  }
  /**
   * @param request
   * @return
   * @throws IOException
   * @throws HttpExecuteException
   * @throws MalformedURLException
   */
  private HttpResponse executeRequest(HttpRequest request) throws IOException {
    if (request.shouldIgnoreResponse()) return new HttpResponse();
    if (!request.hasHeader("Host")) throw new HttpExecuteException("HTTP Host not set");
    String host = request.getHeader("Host").get(0);

    URL url = new URL("http", host, 80, request.getPath());

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(request.getMethod());
    for (Entry<String, List<String>> entry : request.getHeaderPairs().entrySet()) {
      for (String value : entry.getValue()) connection.addRequestProperty(entry.getKey(), value);
    }
    if (request.getMethod().equals("POST")) {
      // Write post data if it exists
      connection.getOutputStream().write(request.getContent());
    }

    HttpResponse response = new HttpResponse();
    response.setResponseCode(connection.getResponseCode());
    response.setResponseMessage(connection.getResponseMessage());
    for (Entry<String, List<String>> entry : connection.getHeaderFields().entrySet()) {
      for (String value : entry.getValue()) response.addHeader(entry.getKey(), value);
    }
    // responseType is eg. the 4 in 403
    int responseType = response.getResponseCode() / 100;
    if (responseType == 4 || responseType == 5)
      response.readAllContent(connection.getErrorStream());
    else response.readAllContent(connection.getInputStream());

    // Add Network Spoofer fingerprint
    response.addHeader("X-Network-Spoofer", "ON");

    return response;
  }
Exemple #5
0
 protected static byte[] readData(
     final HttpURLConnection connection, final boolean error, final boolean gunzip) {
   try {
     InputStream is = null;
     if (error) {
       is = connection.getErrorStream();
     } else {
       is = connection.getInputStream();
       if (gunzip) {
         is = new GZIPInputStream(is);
       }
     }
     if (is == null) {
       if (DEBUG) {
         System.out.println("InputStream is null ?!");
       }
     }
     return readStreamToEnd(is);
   } catch (final Exception e) {
     if (DEBUG) {
       System.err.println("Could not read data!");
     }
     throw new RuntimeException("Could not read data", e);
   }
 }
 /**
  * Reads all available data from the input stream of <code>conn</code> and returns it as byte
  * array. If no input data is available the method returns <code>null</code>.
  *
  * @param conn
  * @return
  * @throws IOException
  */
 protected static byte[] loadBodyDataInBuffer(HttpURLConnection conn) throws IOException {
   InputStream input = conn.getInputStream();
   byte[] data = null;
   try {
     if (Thread.currentThread() instanceof MapSourceListener) {
       // We only throttle atlas downloads, not downloads for the preview map
       long bandwidthLimit = Settings.getInstance().getBandwidthLimit();
       if (bandwidthLimit > 0) {
         input = new ThrottledInputStream(input);
       }
     }
     data = Utilities.getInputBytes(input);
   } catch (IOException e) {
     InputStream errorIn = conn.getErrorStream();
     try {
       byte[] errData = Utilities.getInputBytes(errorIn);
       log.trace(
           "Retrieved " + errData.length + " error bytes for a HTTP " + conn.getResponseCode());
     } catch (Exception ee) {
       log.debug("Error retrieving error stream content: " + e);
     } finally {
       Utilities.closeStream(errorIn);
     }
     throw e;
   } finally {
     Utilities.closeStream(input);
   }
   log.trace("Retrieved " + data.length + " bytes for a HTTP " + conn.getResponseCode());
   if (data.length == 0) return null;
   return data;
 }
 /** {@inheritDoc} */
 @Override
 public Object invoke(
     String methodName, Object argument, Type returnType, Map<String, String> extraHeaders)
     throws Throwable {
   HttpURLConnection connection = prepareConnection(extraHeaders);
   connection.connect();
   try {
     try (OutputStream send = connection.getOutputStream()) {
       super.invoke(methodName, argument, send);
     }
     final boolean useGzip = useGzip(connection);
     // read and return value
     try {
       try (InputStream answer = getStream(connection.getInputStream(), useGzip)) {
         return super.readResponse(returnType, answer);
       }
     } catch (IOException e) {
       try (InputStream answer = getStream(connection.getErrorStream(), useGzip)) {
         return super.readResponse(returnType, answer);
       } catch (IOException ef) {
         throw new HttpException(readErrorString(connection), ef);
       }
     }
   } finally {
     connection.disconnect();
   }
 }
Exemple #8
0
  /**
   * 发�?http请求
   *
   * @param url
   * @param method GET �?POST
   * @param params
   * @return
   */
  public static String openUrl(String url, String method, Bundle params) {
    if (method.equals("GET")) {
      url = url + "?" + encodeUrl(params);
    }
    String response = "";
    try {
      Log.d(LOG_TAG, method + " URL: " + url);
      HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
      conn.setRequestProperty(
          "User-Agent",
          System.getProperties().getProperty("http.agent") + " Renren_Android_SDK_v2.0");
      if (!method.equals("GET")) {
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
      }

      InputStream is = null;
      int responseCode = conn.getResponseCode();
      if (responseCode == 200) {
        is = conn.getInputStream();
      } else {
        is = conn.getErrorStream();
      }
      response = read(is);
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage(), e);
    }
    return response;
  }
  /**
   * Executes refactoring of subcollection workaround.
   *
   * @param collection Name of the collection.
   * @param sub Name of subcollection.
   * @return <code>true</code> if the creation was successful, <code>false</code> otherwise.
   * @throws IOException Exception occurred.
   */
  public boolean runRefactoring(final String sub, final String collection) throws IOException {
    URL url =
        new URL(
            mServers[0] + "?run=" + RQ + "&subcollection=" + sub + "&collectionname=" + collection);
    System.out.println(url.toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    int code = conn.getResponseCode();
    if (code == 200) {
      BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String s;
      while ((s = r.readLine()) != null) {
        System.out.println(s);
      }
      r.close();
    } else {
      BufferedReader r = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
      String s;
      while ((s = r.readLine()) != null) {
        System.out.println(s);
      }
      r.close();
    }

    conn.disconnect();
    return code == 200;
  }
  public static String simulateFormPostForTR(
      BraintreeGateway gateway, Request trParams, Request request, String postUrl) {
    String response = "";
    try {
      String trData = gateway.transparentRedirect().trData(trParams, "http://example.com");
      StringBuilder postData =
          new StringBuilder("tr_data=")
              .append(URLEncoder.encode(trData, "UTF-8"))
              .append("&")
              .append(request.toQueryString());

      URL url = new URL(postUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setInstanceFollowRedirects(false);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");
      connection.addRequestProperty("Accept", "application/xml");
      connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      connection.getOutputStream().write(postData.toString().getBytes("UTF-8"));
      connection.getOutputStream().close();
      if (connection.getResponseCode() == 422) {
        connection.getErrorStream();
      } else {
        connection.getInputStream();
      }

      response = new URL(connection.getHeaderField("Location")).getQuery();
    } catch (IOException e) {
      throw new UnexpectedException(e.getMessage());
    }

    return response;
  }
  /**
   * Executes a POST request for given url and post data
   *
   * @param targetURL
   * @param postData
   * @return result string
   */
  public String executePost(String targetURL, String postData) {
    URL url;
    HttpURLConnection connection = null;
    Log.d(DEBUG_TAG, "executePost(): targetURL=" + targetURL);
    Log.d(DEBUG_TAG, "executePost(): postData=" + postData);
    try {
      // Get binary data
      byte[] outputBytes = postData.getBytes();
      // Create connection
      url = new URL(targetURL);
      connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", "application/json");
      connection.setRequestProperty("Content-Length", "" + Integer.toString(outputBytes.length));
      connection.setUseCaches(false);
      connection.setDoInput(true);
      connection.setDoOutput(true);

      // Send request
      OutputStream wr = connection.getOutputStream();
      wr.write(outputBytes);
      wr.flush();
      wr.close();

      int http_status = connection.getResponseCode();
      Log.d(DEBUG_TAG, "executePost(): http_status=" + http_status);

      InputStream is;

      if (http_status == 200) {
        // Get Response
        is = connection.getInputStream();

      } else {
        // Get Error Response
        is = connection.getErrorStream();
      }

      BufferedReader rd = new BufferedReader(new InputStreamReader(is));
      String line;
      StringBuffer response = new StringBuffer();
      while ((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
      }
      rd.close();
      return response.toString();

    } catch (Exception e) {
      String errorMessage = e.toString();
      Log.d(DEBUG_TAG, "executePost(): " + errorMessage);
      return errorMessage;

    } finally {

      if (connection != null) {
        connection.disconnect();
      }
    }
  }
  private String doHttpTransfer(String url, String data, Map<String, String> headers)
      throws IOException {
    try {
      HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
      for (Map.Entry<String, String> header : headers.entrySet()) {
        connection.setRequestProperty(header.getKey(), header.getValue());
      }
      connection.setRequestProperty("User-Agent", USER_AGENT);
      connection.setDoOutput(true);
      if (data != null) {
        connection.setRequestMethod("POST");
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(data);
        writer.close();
      } else {
        connection.setRequestMethod("GET");
      }

      InputStream inputStream =
          connection.getResponseCode() == 200
              ? connection.getInputStream()
              : connection.getErrorStream();
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
      StringBuilder response = new StringBuilder();
      String line;
      while ((line = reader.readLine()) != null) {
        response.append(line);
      }
      reader.close();
      return response.toString();
    } catch (MalformedURLException e) {
      throw new IOException(e);
    }
  }
    protected Hashtable<String, String> getExecutionResponse( HttpURLConnection con) throws IOException {
        Hashtable<String, String> retVal = new Hashtable<String, String>();
        //System.out.println("SNIConnectionManager, getExecutionResponse," + mUrlAsString);

        int responseCode = con.getResponseCode();
        //System.out.println("SNIConnectionManager, getExecutionResponse, Status Code:" + String.valueOf(responseCode));
        String responseBody = con.getResponseMessage();
        //System.out.println("SNIConnectionManager, getExecutionResponse, Response Body:" + responseBody);
        String contentType =  con.getHeaderField("content-type");
        //System.out.println("SNIConnectionManager, getExecutionResponse, Response contentType:" + contentType);

        retVal.put("statusCode", String.valueOf(responseCode));
        retVal.put("responseMessage", responseBody);
        retVal.put("contentType", (contentType == null ? "" : contentType) );

        /*
        Map<String, List<String>> selects = con.getHeaderFields();
        for(Map.Entry<String, List<String>> entry : selects.entrySet()) {
            String key = entry.getKey();
            List<String> value = entry.getValue();
            System.out.println("SNIConnectionManager, getExecutionResponse, ** HEADER KEY *******->" + key);
            System.out.println("SNIConnectionManager, getExecutionResponse, ** HEADER VALUE *****->" + value.toString());
        }
        */

        if (responseCode>= HttpStatus.SC_BAD_REQUEST)
            retVal.put("responseBody", Utilities.convertStreamToString(con.getErrorStream()));
        else
            retVal.put("responseBody", Utilities.convertStreamToString(con.getInputStream()));

        return retVal;
    }
Exemple #14
0
  /**
   * Utility to handle the output response in case of errors.
   *
   * @param conn connection to the Rexster Interface
   * @param type type of data saved (vertices or edges)
   */
  private static void handleResponse(HttpURLConnection conn, String type)
      throws IOException, InterruptedException {

    if (conn.getResponseCode() != 200) {
      InputStream is = conn.getErrorStream();
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));

      JSONObject obj = new JSONObject(rd);
      StringBuffer sb = new StringBuffer("Error occured while saving " + type + ";");
      String aux;
      while ((aux = rd.readLine()) != null) {
        sb.append(aux);
      }
      sb.append(obj);

      /*
      try {
        LOG.info("--> " + obj);
        String message = obj.getString("message");
        sb.append(" ");
        sb.append(message);
      } catch (JSONException e) {
        LOG.error("Unable to extract the error message.");
      }
      */
      rd.close();

      throw new InterruptedException(sb.toString());
    }
  }
Exemple #15
0
  private String getBlobURL() {
    String blobUrl = "";
    HttpURLConnection httpUrlConnection = null;

    try {
      httpUrlConnection = (HttpURLConnection) new URL(Constants.UPLOAD_FORM_URL).openConnection();
      switch (httpUrlConnection.getResponseCode()) {
        case HttpURLConnection.HTTP_OK:
          InputStream in = new BufferedInputStream(httpUrlConnection.getInputStream());

          blobUrl = NetworkUtils.readStream(in);
          break;
        case HttpURLConnection.HTTP_NOT_FOUND:
          InputStream err = new BufferedInputStream(httpUrlConnection.getErrorStream());
          blobUrl = NetworkUtils.readStream(err);
          break;
      }
    } catch (MalformedURLException exception) {
      Log.e(TAG, "MalformedURLException");
    } catch (IOException exception) {
      Log.e(TAG, "IOException");
    } finally {
      if (null != httpUrlConnection) httpUrlConnection.disconnect();
    }
    return blobUrl;
  }
  public static String post(String url, byte[] body, String contentType) throws IOException {
    try {
      HttpURLConnection conn = openConnection(url);
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      if (contentType != null) {
        conn.setRequestProperty("Content-Type", contentType);
      }
      conn.getOutputStream().write(body);

      if (conn.getResponseCode() != 200) {
        logger.error(
            "response error {},request {}",
            IOUtils.toString(conn.getErrorStream()),
            new String(body));
        return "";
      }

      contentType = conn.getContentType();
      String encoding = "utf-8";
      if (contentType != null && contentType.indexOf("charset=") > 0) {
        encoding = contentType.split("charset=")[1];
      }

      InputStream is = conn.getInputStream();
      byte[] resp = IOUtils.toByteArray(is);
      conn.disconnect();
      return new String(resp, encoding);
    } catch (MalformedURLException | URISyntaxException e) {
      logger.error("", e);
      return "";
    }
  }
 @Override
 public InputStream getContent() throws IOException {
   HttpURLConnection connection = this.connection;
   return HttpStatusCodes.isSuccess(responseCode)
       ? connection.getInputStream()
       : connection.getErrorStream();
 }
 /**
  * 发起GET请求
  *
  * @param link URL
  * @return API返回JSON数据
  * @throws Exception 异常
  */
 private JSONObject get(String link) throws Exception {
   LogUtil.i("HTTP.GET", link);
   URL url = new URL(link);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   // conn.setRequestProperty("User-agent", "Mozilla/5.0 (Linux; Android 4.2.1; Nexus 7
   // Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19");
   conn.setReadTimeout(5000);
   conn.setConnectTimeout(10000);
   if (token != null) {
     conn.setRequestProperty("token", token);
     LogUtil.i("HTTP.GET", token);
   }
   InputStream is = conn.getResponseCode() >= 400 ? conn.getErrorStream() : conn.getInputStream();
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   int len;
   byte buffer[] = new byte[1024];
   while ((len = is.read(buffer)) != -1) {
     os.write(buffer, 0, len);
   }
   is.close();
   os.close();
   conn.disconnect();
   String content = new String(os.toByteArray());
   LogUtil.i("HTTP.GET", content);
   JSONObject jsonObject = new JSONObject(content);
   checkCode(jsonObject);
   return jsonObject;
 }
Exemple #19
0
  /**
   * Read server response from HTTP connection and return task description.
   *
   * @throws Exception in case of error
   */
  private Task getResponse(HttpURLConnection connection) throws Exception {
    int responseCode = connection.getResponseCode();
    if (responseCode == 200) {
      InputStream inputStream = connection.getInputStream();
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
      return new Task(reader);
    } else if (responseCode == 401) {
      throw new Exception("HTTP 401 Unauthorized. Please check your application id and password");
    } else if (responseCode == 407) {
      throw new Exception("HTTP 407. Proxy authentication error");
    } else {
      String message = "";
      try {
        InputStream errorStream = connection.getErrorStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));

        // Parse xml error response
        InputSource source = new InputSource();
        source.setCharacterStream(reader);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(source);

        NodeList error = doc.getElementsByTagName("error");
        Element err = (Element) error.item(0);

        message = err.getTextContent();
      } catch (Exception e) {
        throw new Exception("Error getting server response");
      }

      throw new Exception("Error: " + message);
    }
  }
  public static String performGetRequest(String urlString) throws IOException {

    StringBuffer response = new StringBuffer();
    URLConnection conn = null;
    InputStream is = null;
    String errorResponse = "NA";

    try {
      URL url = new URL(urlString);
      conn = url.openConnection();

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

      while ((inputLine = br.readLine()) != null) {
        System.out.println(inputLine);
        response.append(inputLine);
      }
      br.close();
      System.out.println("Done");

    } catch (Exception e) {

      if (conn instanceof HttpURLConnection) {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        int statusCode = httpConn.getResponseCode();
        if (statusCode != 200) {
          is = httpConn.getErrorStream();
          errorResponse = IOUtils.toString(is);
        }
      }
    }

    return (response.length() > 0) ? response.toString() : errorResponse;
  }
  /**
   * 实现发送数据功能的方法,是整个类的核心. 我(fins)借鉴了 cobra 组件的 org.lobobrowser.html.test.SimpleHttpRequest 类中的同名方法.
   * 略作改动.
   */
  protected void sendSync(String content) throws IOException {
    if (hasSent()) {
      log(Level.WARNING, "This XmlHttpRequestHelper Object has sent", null);
      return;
    }
    try {
      URLConnection c;
      c = this.connection;

      if (c == null) {
        log(Level.WARNING, "Please open XmlHttpRequestHelper first.", null);
        return;
      }
      setSent(true);
      initConnectionRequestHeader(c);
      int istatus;
      String istatusText;
      InputStream err;
      if (c instanceof HttpURLConnection) {
        HttpURLConnection hc = (HttpURLConnection) c;
        String method = this.requestMethod == null ? DEFAULT_REQUEST_METHOD : this.requestMethod;

        method = method.toUpperCase();
        hc.setRequestMethod(method);
        if ("POST".equals(method) && content != null) {
          hc.setDoOutput(true);
          byte[] contentBytes = content.getBytes(this.getPostCharset());
          hc.setFixedLengthStreamingMode(contentBytes.length);
          OutputStream out = hc.getOutputStream();
          try {
            out.write(contentBytes);
          } finally {
            out.flush();
          }
        }
        istatus = hc.getResponseCode();
        istatusText = hc.getResponseMessage();
        err = hc.getErrorStream();
      } else {
        istatus = 0;
        istatusText = "";
        err = null;
      }

      this.responseHeaders = getConnectionResponseHeaders(c);
      this.responseHeadersMap = c.getHeaderFields();

      this.changeState(XmlHttpRequestHelper.STATE_LOADED, istatus, istatusText, null);
      InputStream in = err == null ? c.getInputStream() : err;
      int contentLength = c.getContentLength();

      this.changeState(XmlHttpRequestHelper.STATE_INTERACTIVE, istatus, istatusText, null);
      byte[] bytes = loadStream(in, contentLength == -1 ? 4096 : contentLength);
      this.changeState(XmlHttpRequestHelper.STATE_COMPLETE, istatus, istatusText, bytes);
    } finally {

      this.connection = null;
      setSent(false);
    }
  }
 /**
  * 发起PUT请求
  *
  * @param link URL
  * @param datas 传递给服务器的参数
  * @return API返回JSON数据
  * @throws Exception 异常
  */
 private JSONObject put(String link, Object datas) throws Exception {
   LogUtil.i("HTTP.PUT", link);
   //        StringBuffer data = new StringBuffer();
   //        if (datas != null) {
   //            Iterator<Map.Entry<String, Object>> it = datas.entrySet().iterator();
   //            while (it.hasNext()) {
   //                Map.Entry<String, Object> pairs = it.next();
   //                if (pairs.getValue() instanceof Object[]) {
   //                    for (Object d : (Object[]) pairs.getValue()) {
   //                        data.append("&" + pairs.getKey() + "=" + d.toString());
   //                    }
   //                } else if (pairs.getValue() instanceof Collection) {
   //                    for (Object d : (Collection) pairs.getValue()) {
   //                        data.append("&" + pairs.getKey() + "=" + d.toString());
   //                    }
   //                } else {
   //                    data.append("&" + pairs.getKey() + "=" + pairs.getValue().toString());
   //                }
   //            }
   //        }
   String data = "";
   if (datas instanceof Map) {
     JSONObject json = new JSONObject((Map) datas);
     data = json.toString();
   } else if (datas instanceof JSONObject) {
     data = datas.toString();
   }
   LogUtil.i("HTTP.PUT", data);
   URL url = new URL(link);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("PUT");
   if (token != null) {
     conn.setRequestProperty("token", token);
     LogUtil.i("HTTP.PUT", token);
   }
   conn.setRequestProperty("Content-Type", "application/json");
   conn.setReadTimeout(5000);
   conn.setConnectTimeout(10000);
   conn.setDoInput(true);
   conn.setDoOutput(true);
   OutputStream out = conn.getOutputStream();
   out.write(data.getBytes());
   out.flush();
   out.close();
   InputStream is = conn.getResponseCode() >= 400 ? conn.getErrorStream() : conn.getInputStream();
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   int len;
   byte buffer[] = new byte[1024];
   while ((len = is.read(buffer)) != -1) {
     os.write(buffer, 0, len);
   }
   is.close();
   os.close();
   conn.disconnect();
   String content = new String(os.toByteArray());
   LogUtil.i("HTTP.PUT", content);
   JSONObject jsonObject = new JSONObject(content);
   checkCode(jsonObject);
   return jsonObject;
 }
Exemple #23
0
 /**
  * 显示Response消息
  *
  * @param connection
  * @param CharsetName
  * @return
  * @throws URISyntaxException
  * @throws IOException
  */
 private String response(final HttpURLConnection connection, String encoding)
     throws URISyntaxException, IOException, Exception {
   InputStream in = null;
   StringBuilder sb = new StringBuilder(1024);
   BufferedReader br = null;
   try {
     if (200 == connection.getResponseCode()) {
       in = connection.getInputStream();
       sb.append(new String(read(in), encoding));
     } else {
       in = connection.getErrorStream();
       sb.append(new String(read(in), encoding));
     }
     LogUtil.writeLog("HTTP Return Status-Code:[" + connection.getResponseCode() + "]");
     return sb.toString();
   } catch (Exception e) {
     throw e;
   } finally {
     if (null != br) {
       br.close();
     }
     if (null != in) {
       in.close();
     }
     if (null != connection) {
       connection.disconnect();
     }
   }
 }
  @Override
  public <T> T invoke(Type returnType, Object _url, Object obj) {

    try {
      URL url = new URL(_url.toString());
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.addRequestProperty("Content-Type", Configure.Request.contentType);
      connection.addRequestProperty("User-Agent", Configure.Request.userAgent);
      connection.setConnectTimeout(Configure.Request.http_connection_timeout);
      connection.setReadTimeout(Configure.Request.http_read_timeout);
      connection.setRequestMethod("POST");
      connection.setDoOutput(true);

      objectMapper.writeValue(connection.getOutputStream(), obj);
      int status = connection.getResponseCode();

      if (status == 200) {
        T res = buildResponse(returnType, connection.getInputStream());
        return res;

      } else {
        BufferedReader reader =
            new BufferedReader(new InputStreamReader(connection.getErrorStream(), "utf-8"));
        StringBuffer message = new StringBuffer();
        while (reader.ready()) {
          message.append(reader.readLine());
        }
        throw new RuntimeException(message.toString());
      }
    } catch (MalformedURLException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Exemple #25
0
  /**
   * This method will test the return type to make sure that it is between 200 (inclusive) and 300
   * (exclusive), i.e. that it is "successful". If it is not then it will throw an {@link
   * RequestFailureException} with the response code and message from the error stream.
   *
   * @param connection
   * @throws RequestFailureException
   * @throws IOException
   * @see HttpURLConnection#getResponseCode()
   * @see HttpURLConnection#getErrorStream()
   */
  private void testResponseCode(HttpURLConnection connection)
      throws RequestFailureException, IOException {
    int responseCode = connection.getResponseCode();
    if (responseCode < 200 || responseCode >= 300) {
      // Not one of the OK response codes so get the message off the error stream and throw an
      // exception
      InputStream errorStream = connection.getErrorStream();
      String errorStreamString = null;
      String message = null;
      if (errorStream != null) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int read = -1;
        while ((read = errorStream.read()) != -1) {
          outputStream.write(read);
        }

        errorStreamString = outputStream.toString(getCharset(connection.getContentType()));
        // The content of the error stream coming from Massive seems to vary in structure (HTML,
        // JSON) see if it is is JSON and get a good message or use it as is
        message = parseErrorObject(errorStreamString);
      }
      throw new RequestFailureException(
          responseCode, message, connection.getURL(), errorStreamString);
    }
  }
    public OutputStream ExecuteHttpAsStream(KZHttpMethod method) throws Exception
    {
        HttpURLConnection con = CreateConnectionThatHandlesRedirects(method);
        if (method ==KZHttpMethod.POST || method ==KZHttpMethod.PUT && mBodyAsStream !=null) {
            con.setDoOutput(true);

            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1*1024*1024;

            DataOutputStream dos = new DataOutputStream( con.getOutputStream() );
            bytesAvailable = mBodyAsStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            bytesRead = mBodyAsStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0)
            {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = mBodyAsStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = mBodyAsStream.read(buffer, 0, bufferSize);
            }
            mBodyAsStream.close();
            dos.flush();
            dos.close();
        }


        LastResponseCode = con.getResponseCode();
        LastResponseMessage = con.getResponseMessage();

        if (LastResponseCode>= HttpStatus.SC_BAD_REQUEST)
        {
            LastResponseBody = Utilities.convertStreamToString(con.getErrorStream());
            return null;
        }
        else
        {
            int dataRead = 0;
            int CHUNK_SIZE = 8192;                   // TCP/IP packet size
            byte[] dataChunk = new byte[CHUNK_SIZE]; // byte array for storing temporary data.

            OutputStream fos = new ByteArrayOutputStream();

            BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
            InputStreamReader isr = new InputStreamReader( bis );
            while (dataRead >= 0)
            {
                dataRead = bis.read(dataChunk,0,CHUNK_SIZE);
                // only write out if there is data to be read
                if ( dataRead > 0 ) {
                    fos.write(dataChunk, 0, dataRead);
                }
            }
            bis.close();
            fos.close();
            return fos;
        }
    }
 private InputStream getInputStream(HttpURLConnection uc) throws IOException {
   if (uc.getResponseCode() < 400) {
     return uc.getInputStream();
   } else {
     InputStream ein = uc.getErrorStream();
     return (ein != null) ? ein : new ByteArrayInputStream(new byte[0]);
   }
 }
Exemple #28
0
  @Test
  public void networkFailureResponseSourceHeader() throws Exception {
    server.enqueue(new MockResponse().setResponseCode(404));

    HttpURLConnection connection = factory.open(server.getUrl("/"));
    assertResponseHeader(connection, "NETWORK 404");
    connection.getErrorStream().close();
  }
 @Override
 public InputStream getInputStream() throws IOException {
   if (inputStream == null) {
     outClosed = true;
     JsonArray users =
         new JsonParser()
             .parse(new String(outputStream.toByteArray(), Charsets.UTF_8))
             .getAsJsonArray();
     StringBuilder reply = new StringBuilder("[");
     StringBuilder missingUsers = new StringBuilder("[");
     for (JsonElement user : users) {
       String username = user.getAsString().toLowerCase();
       String info = cache.getIfPresent(username);
       if (info != null) {
         reply.append(info).append(",");
       } else {
         missingUsers.append("\"").append(username).append("\"").append(",");
       }
     }
     if (missingUsers.length() > 1) {
       missingUsers.deleteCharAt(missingUsers.length() - 1).append("]");
     }
     if (missingUsers.length() > 2) {
       HttpURLConnection connection;
       if (proxy == null) {
         connection = (HttpURLConnection) cachedStreamHandler.getDefaultConnection(url);
       } else {
         connection = (HttpURLConnection) cachedStreamHandler.getDefaultConnection(url, proxy);
       }
       connection.setRequestMethod("POST");
       connection.setRequestProperty("Content-Type", "application/json");
       connection.setDoInput(true);
       connection.setDoOutput(true);
       OutputStream out = connection.getOutputStream();
       out.write(missingUsers.toString().getBytes(Charsets.UTF_8));
       out.flush();
       out.close();
       JsonArray newUsers =
           new JsonParser()
               .parse(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8))
               .getAsJsonArray();
       for (JsonElement user : newUsers) {
         JsonObject u = user.getAsJsonObject();
         cache.put(u.get("name").getAsString(), u.toString());
         reply.append(u.toString()).append(",");
       }
       responseCode = connection.getResponseCode();
       errorStream = connection.getErrorStream();
     } else {
       responseCode = HTTP_OK;
     }
     if (reply.length() > 1) {
       reply.deleteCharAt(reply.length() - 1);
     }
     inputStream = new ByteArrayInputStream(reply.append("]").toString().getBytes(Charsets.UTF_8));
   }
   return inputStream;
 }
  public static int methodUrl(
      String path,
      ByteChunk out,
      int readTimeout,
      Map<String, List<String>> reqHead,
      Map<String, List<String>> resHead,
      String method)
      throws IOException {

    URL url = new URL(path);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setUseCaches(false);
    connection.setReadTimeout(readTimeout);
    connection.setRequestMethod(method);
    if (reqHead != null) {
      for (Map.Entry<String, List<String>> entry : reqHead.entrySet()) {
        StringBuilder valueList = new StringBuilder();
        for (String value : entry.getValue()) {
          if (valueList.length() > 0) {
            valueList.append(',');
          }
          valueList.append(value);
        }
        connection.setRequestProperty(entry.getKey(), valueList.toString());
      }
    }
    connection.connect();
    int rc = connection.getResponseCode();
    if (resHead != null) {
      Map<String, List<String>> head = connection.getHeaderFields();
      resHead.putAll(head);
    }
    InputStream is;
    if (rc < 400) {
      is = connection.getInputStream();
    } else {
      is = connection.getErrorStream();
    }
    BufferedInputStream bis = null;
    try {
      bis = new BufferedInputStream(is);
      byte[] buf = new byte[2048];
      int rd = 0;
      while ((rd = bis.read(buf)) > 0) {
        out.append(buf, 0, rd);
      }
    } finally {
      if (bis != null) {
        try {
          bis.close();
        } catch (IOException e) {
          // Ignore
        }
      }
    }
    return rc;
  }