示例#1
1
 private Map<String, String> parseHeaders(HttpURLConnection conn) {
   Map<String, String> headers = new HashMap<String, String>();
   for (String key : conn.getHeaderFields().keySet()) {
     headers.put(key, conn.getHeaderFields().get(key).get(0));
   }
   return headers;
 }
  @Override
  public Object getResponseContent(HttpURLConnection conn) throws IOException, ClientException {
    Exception error = null;
    InputStream input;
    if (conn == null) {
      throw new ClientException("Network error", null);
    }
    try {
      input = conn.getInputStream();
    } catch (Exception e) {
      Log.w("AndroidClient", e.toString());
      error = e;
      input = conn.getErrorStream();
    }
    Map<String, List<String>> headerFields = conn.getHeaderFields();
    if (headerFields != null) {
      Log.i("Base", headerFields.toString());
    }
    if (input != null) {
      Log.i("Base", "class " + input.getClass().getName());
    }
    final int responseCode = conn.getResponseCode();
    if (responseCode == 404) throw new ClientException("Item not found", null);
    if (input != null
        && input.getClass().getName().startsWith("libcore.net.http.HttpResponseCache")) {
      input = new GZIPInputStream(input);
    }

    final StringBuilder builder = new StringBuilder();
    if (input != null) {
      final BufferedReader br = new BufferedReader(new InputStreamReader(input));
      try {
        String output;
        while ((output = br.readLine()) != null) builder.append(output);

      } finally {
        br.close();
      }
    }
    conn.disconnect();

    if (responseCode >= 300 || error != null)
      throw new ClientException(
          responseCode,
          (error != null ? error.getMessage() : "") + ", response: " + builder,
          error);

    if (builder.length() == 0) return null;
    try {
      if (conn.getContentType().contains(JSON_MIME_TYPE)) return new JSONObject(builder.toString());
    } catch (JSONException e) {
      throw new ClientException(e);
    }
    return builder.toString();
  }
示例#3
0
    public void getFileInfo() {
      myMessage.stateChanged("DOWNLOADFILEINFO");
      URL url;
      try {
        url = new URL(myProperties.getProperty("DOWNLOADURL"));
        System.out.println(myProperties.getProperty("DOWNLOADURL"));
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int contentLength = httpConn.getContentLength();
        Map<String, List<String>> theMap = httpConn.getHeaderFields();
        Set keys = theMap.keySet();
        for (Iterator i = keys.iterator(); i.hasNext(); ) {
          String key = (String) i.next();
          String value = theMap.get(key).toString();
          myMessage.messageChanged(key + " = " + value);
        }

        if (contentLength == -1) {
          myMessage.messageChanged("unknown content length");
        } else {
          myMessage.messageChanged("content length: " + contentLength + " bytes");
        }
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
示例#4
0
 /**
  * This method will issue a HEAD to all of the assets in massive and returns the {@link
  * HttpURLConnection#getHeaderFields()}.
  *
  * @return The {@link HttpURLConnection#getHeaderFields()} for the HEAD request
  * @throws IOException
  * @throws RequestFailureException if the response code is not OK
  */
 public Map<String, List<String>> getAllAssetsMetadata()
     throws IOException, RequestFailureException {
   HttpURLConnection connection = createHttpURLConnectionToMassive("/assets");
   connection.setRequestMethod("HEAD");
   testResponseCode(connection);
   return connection.getHeaderFields();
 }
 private InBoundHeaders getInBoundHeaders(HttpURLConnection uc) {
   InBoundHeaders headers = new InBoundHeaders();
   for (Map.Entry<String, List<String>> e : uc.getHeaderFields().entrySet()) {
     if (e.getKey() != null) headers.put(e.getKey(), e.getValue());
   }
   return headers;
 }
  @Test
  public void post() throws Exception {
    given(connection.getURL()).willReturn(new URL(URL));
    given(connection.getResponseCode()).willReturn(200);
    given(connection.getResponseMessage()).willReturn("OK");
    Map<String, List<String>> responseHeaderFields = new LinkedHashMap<String, List<String>>();
    responseHeaderFields.put("Set-Cookie", Arrays.asList("aaa"));
    given(connection.getHeaderFields()).willReturn(responseHeaderFields);

    Request request =
        new Request(
            "POST",
            URL,
            Arrays.asList(new Header("Hoge", "Piyo")),
            new FormUrlEncodedTypedOutput().addField("foo", "bar"));

    Response response = underTest.execute(request);

    verify(connection).setRequestMethod("POST");
    verify(connection).addRequestProperty("Hoge", "Piyo");
    verify(connection).getOutputStream();

    assertThat(response.getUrl()).isEqualTo(URL);
    assertThat(response.getStatus()).isEqualTo(200);
    assertThat(response.getReason()).isEqualTo("OK");
    assertThat(response.getHeaders()).isEqualTo(Arrays.asList(new Header("Set-Cookie", "aaa")));
    assertThat(output.toString("UTF-8")).isEqualTo("foo=bar");
  }
示例#7
0
 /**
  * Do a http operation
  *
  * @param urlConnection the HttpURLConnection to be used
  * @param inputData if not null,will be written to the urlconnection.
  * @param hasOutput if true, read content back from the urlconnection
  * @return Response
  * @throws IOException
  */
 public static HttpResponse doOperation(
     HttpURLConnection urlConnection, byte[] inputData, boolean hasOutput) throws IOException {
   HttpResponse response = null;
   InputStream inputStream = null;
   OutputStream outputStream = null;
   byte[] payload = null;
   try {
     if (inputData != null) {
       urlConnection.setDoOutput(true);
       outputStream = urlConnection.getOutputStream();
       outputStream.write(inputData);
     }
     /*
      * Get response code first. HttpURLConnection does not allow to
      * read inputstream if response code is not success code
      */
     int responseCode = urlConnection.getResponseCode();
     if (hasOutput && isSuccessCode(responseCode)) {
       payload = getBytes(urlConnection.getInputStream());
     }
     response = new HttpResponse(urlConnection.getHeaderFields(), responseCode, payload);
   } finally {
     Util.close(inputStream);
     Util.close(outputStream);
   }
   return response;
 }
  public Map<String, List<String>> headHTTPRequest(String uri, String ifModSince) {
    URL url = null;
    HttpURLConnection connection = null;

    Map<String, List<String>> map = null;
    try {

      url = new URL(uri);
      connection = (HttpURLConnection) url.openConnection();
      connection.setRequestProperty("User-Agent", "cis455Crawler");
      // connection.setDoOutput(true);
      connection.setConnectTimeout(5000);
      connection.setRequestMethod("HEAD");
      if (ifModSince != null) {
        connection.setRequestProperty("If-Modified-Since", ifModSince);
      }
      connection.setDoOutput(true);
      map = connection.getHeaderFields();
    } catch (MalformedURLException e) {
      System.out.println("MalformedURLException");
    } catch (IOException e) {
      System.out.println("IOException");
    }
    return map;
  }
  public static void xs3_upload_by_url(URL xs3_url, String file_path) throws IOException {

    BufferedInputStream xs3_instream = null;
    BufferedOutputStream xs3_outstream = null;
    try {
      HttpURLConnection http_conn = (HttpURLConnection) xs3_url.openConnection();
      http_conn.setDoOutput(true);
      http_conn.setRequestMethod("PUT");

      http_conn.setRequestProperty("Content-Type", "image/jpeg");
      http_conn.setRequestProperty("x-amz-acl", "public-read");

      xs3_outstream = new BufferedOutputStream(http_conn.getOutputStream());
      xs3_instream = new BufferedInputStream(new FileInputStream(new File(file_path)));

      byte[] buffer = new byte[1024];
      int xs3_offset = 0;
      while ((xs3_offset = xs3_instream.read(buffer)) != -1) {
        xs3_outstream.write(buffer, 0, xs3_offset);
        xs3_outstream.flush();
      }

      System.out.println("xs3_http_status : " + http_conn.getResponseCode());
      System.out.println("xs3_http_headers: " + http_conn.getHeaderFields());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (null != xs3_outstream) xs3_outstream.close();
      if (null != xs3_instream) xs3_instream.close();
    }
  }
示例#10
0
 private static HttpResponse getHttpResponse(HttpURLConnection connection, HttpRequest httpRequest)
     throws IOException {
   BufferedReader in = null; // 站在机器的角度,从远端读入内存
   // OutputStream out = null;//站在机器的角度,从内存写入远端
   try {
     httpRequest.responseBody(connection); // 写入请求参数值(对于GET不需要,)
     String charset = getCharset(connection); // 获取content type
     StringBuilder sb = new StringBuilder();
     // 读取http返回的结果
     in =
         new BufferedReader(
             new InputStreamReader(
                 connection.getInputStream(),
                 charset == null ? Constant.DEFAULT_CHARSET : charset));
     String line = null;
     while ((line = in.readLine()) != null) {
       sb.append(CTRL).append(line);
     }
     return HttpResponse.createInstance()
         .setReturnCode(connection.getResponseCode())
         .setResponseBody(sb.toString())
         .setHeaders(connection.getHeaderFields())
         .build();
   } finally {
     IOUtil.closeQuietly(in); // 关闭流 IOUtil.closeQuietly(out);
   }
 }
示例#11
0
  public static void main(String[] args) throws Exception {
    String username = System.getProperty("username", "");
    String password = System.getProperty("password", "");

    String authorizationString = username + ":" + password;

    byte[] encodedBytes = Base64.encodeBase64(authorizationString.getBytes());

    String encodedString = new String(encodedBytes);

    System.out.println("Encoded string: " + encodedString);

    String url = "http://example.com";

    HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
    httpConnection.setRequestMethod("GET");

    int status = httpConnection.getResponseCode();
    System.out.println(status);

    for (Entry<String, List<String>> header : httpConnection.getHeaderFields().entrySet()) {
      System.out.println(header.getKey() + "=" + header.getValue());
    }

    httpConnection.disconnect();
  }
示例#12
0
  /**
   * @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;
  }
示例#13
0
 public static String getHtmlSourceByGet(String spec, String charsetName, StringBuffer cookie)
     throws Exception {
   byte[] bytes = null;
   for (int i = 3; i > 0; --i) {
     try {
       URL url = new URL(spec);
       HttpURLConnection.setFollowRedirects(false);
       HttpURLConnection connection = (HttpURLConnection) url.openConnection();
       if (cookie != null) {
         connection.setRequestProperty("Cookie", cookie.toString());
       }
       InputStream is = connection.getInputStream();
       bytes = readToEnd(is);
       is.close();
       if (cookie != null) {
         List<String> cookieList = connection.getHeaderFields().get("Set-Cookie");
         if (cookieList != null) {
           for (String c : cookieList) {
             cookie.append(c);
             cookie.append("; ");
           }
         }
       }
       connection.disconnect();
       break;
     } catch (Exception e) {
       if (i == 1) {
         throw e;
       }
       Thread.sleep((4 - i) * 1024);
     }
   }
   return encodeHtmlSource(bytes, charsetName);
 }
  static String getResponseHeaderByKey(HttpURLConnection http, String key) {
    if (null == key) {
      return null;
    }

    Map<String, List<String>> headers = http.getHeaderFields();
    if (null == headers) {
      return null;
    }

    String header = null;

    for (Entry<String, List<String>> entry : headers.entrySet()) {
      if (key.equalsIgnoreCase(entry.getKey())) {
        if ("set-cookie".equalsIgnoreCase(key)) {
          header = combinCookies(entry.getValue(), http.getURL().getHost());
        } else {
          header = listToString(entry.getValue(), ",");
        }
        break;
      }
    }

    return header;
  }
示例#15
0
    /**
     * Do a http operation
     *
     * @param urlConnection the HttpURLConnection to be used
     * @param inputData if not null,will be written to the urlconnection.
     * @param hasOutput if true, read content back from the urlconnection
     * @return Response
     */
    private Response doOperation(
        HttpURLConnection urlConnection, byte[] inputData, boolean hasOutput) {
      Response response = null;
      InputStream inputStream = null;
      OutputStream outputStream = null;
      byte[] payload = null;
      try {
        if (inputData != null) {
          urlConnection.setDoOutput(true);
          outputStream = urlConnection.getOutputStream();
          outputStream.write(inputData);
        }
        if (hasOutput) {
          inputStream = urlConnection.getInputStream();
          payload = Util.readFileContents(urlConnection.getInputStream());
        }
        response =
            new Response(urlConnection.getHeaderFields(), urlConnection.getResponseCode(), payload);

      } catch (IOException e) {
        log.error("Error calling service", e);
      } finally {
        Util.close(inputStream);
        Util.close(outputStream);
      }
      return response;
    }
  public InputStream invokeClientInbound(HttpURLConnection httpConnection) throws IOException {
    // XXX fill this in...
    Map<String, DataHandler> attachments = new HashMap<String, DataHandler>();

    Map<String, Object> httpProperties = new HashMap<String, Object>();
    httpProperties.put(HTTP_RESPONSE_CODE, Integer.valueOf(httpConnection.getResponseCode()));
    httpProperties.put(HTTP_RESPONSE_HEADERS, httpConnection.getHeaderFields());

    prepare(httpProperties, /*request=*/ false);

    if (!invokeInbound(httpConnection.getInputStream(), attachments)) {
      if (getProtocolException() != null) {
        reverseDirection();
        invokeInboundFaultHandlers();

        if (getRuntimeException() != null) throw getRuntimeException();
      } else if (getRuntimeException() != null) {
        closeClient();
        throw getRuntimeException();
      }
    }

    // XXX
    closeClient();
    return finish();
  }
示例#17
0
 private void addHeadersToResponse(BasicHttpResponse response, HttpURLConnection connection) {
   for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
     if (header.getKey() != null) {
       Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
       response.addHeader(h);
     }
   }
 }
示例#18
0
  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;
  }
示例#19
0
文件: NetUtils.java 项目: jq/zhong
  public static String fetchHtmlPage(int id, String link, String coding) throws IOException {
    URL url = new URL(link);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestProperty(
        "User-Agent",
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3");
    connection.setRequestProperty(
        "Accept",
        "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
    connection.setRequestProperty("Accept-Language", "en-us");
    connection.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
    connection.setRequestProperty("Keep-Alive", "300");
    connection.setRequestProperty("Connection", "keep-alive");

    if (id != -1) {
      if (sCookie.get(id) != null) {
        connection.setRequestProperty("Cookie", sCookie.get(id));
      }
    }

    connection.setConnectTimeout(CONNECT_TIMEOUT);
    connection.connect();

    if (Utils.DEBUG) {
      Utils.D("Reply headers:");
      Map replyHeaders = connection.getHeaderFields();
      Iterator it = replyHeaders.entrySet().iterator();
      Map.Entry pairs = (Map.Entry) it.next();
      Utils.D(pairs.getKey() + " = " + pairs.getValue());
      Utils.D("End reply headers");
    }

    String cookie = connection.getHeaderField("Set-Cookie");

    if (id != -1) {
      if (!TextUtils.isEmpty(cookie)) {
        sCookie.put(id, cookie);
      }
    }

    StringBuilder builder = new StringBuilder(INITIAL_BUFFER_SIZE);

    InputStreamReader is =
        coding != null
            ? new InputStreamReader(connection.getInputStream(), coding)
            : new InputStreamReader(connection.getInputStream());

    BufferedReader reader = new BufferedReader(is);

    String line = null;
    while ((line = reader.readLine()) != null) {
      builder.append(line);
      builder.append('\n');
    }
    return builder.toString();
  }
示例#20
0
 public HttpResponse(HttpURLConnection urlConnection, byte[] body) {
   try {
     this.status = urlConnection.getResponseCode();
     this.url = urlConnection.getURL().toString();
   } catch (IOException e) {
     e.printStackTrace();
   }
   this.headers = urlConnection.getHeaderFields();
   this.body = body;
 }
示例#21
0
  /**
   * Method description
   *
   * @param request
   * @param response
   */
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) {
    BufferedInputStream webToProxyBuf = null;
    BufferedOutputStream proxyToClientBuf = null;
    HttpURLConnection con;

    try {
      URL url = urlProvider.getProxyURL();

      AssertUtil.assertIsNotNull(url);

      if (logger.isInfoEnabled()) {
        logger.info("proxy request for {}", url.toString());
      }

      con = (HttpURLConnection) url.openConnection();
      con.setDoOutput(true);
      con.setDoInput(true);
      con.setUseCaches(true);

      for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) {
        String headerName = e.nextElement().toString();

        con.setRequestProperty(headerName, request.getHeader(headerName));
      }

      con.connect();
      response.setStatus(con.getResponseCode());

      for (Iterator i = con.getHeaderFields().entrySet().iterator(); i.hasNext(); ) {
        Map.Entry mapEntry = (Map.Entry) i.next();

        if (mapEntry.getKey() != null) {
          response.setHeader(
              mapEntry.getKey().toString(), ((List) mapEntry.getValue()).get(0).toString());
        }
      }

      webToProxyBuf = new BufferedInputStream(con.getInputStream());
      proxyToClientBuf = new BufferedOutputStream(response.getOutputStream());

      int oneByte;

      while ((oneByte = webToProxyBuf.read()) != -1) {
        proxyToClientBuf.write(oneByte);
      }

      con.disconnect();
    } catch (Exception ex) {
      logger.error("could not proxy request", ex);
    } finally {
      IOUtil.close(webToProxyBuf);
      IOUtil.close(proxyToClientBuf);
    }
  }
示例#22
0
 /**
  * Copy headers from an HTTP connection to an InternetHeaders object
  *
  * @param aConn Connection - source. May not be <code>null</code>.
  * @param aHeaders Headers - destination. May not be <code>null</code>.
  */
 public static void copyHttpHeaders(
     @Nonnull final HttpURLConnection aConn, @Nonnull final InternetHeaders aHeaders) {
   for (final Map.Entry<String, List<String>> aConnHeader : aConn.getHeaderFields().entrySet()) {
     final String sHeaderName = aConnHeader.getKey();
     if (sHeaderName != null)
       for (final String sHeaderValue : aConnHeader.getValue()) {
         if (aHeaders.getHeader(sHeaderName) == null)
           aHeaders.setHeader(sHeaderName, sHeaderValue);
         else aHeaders.addHeader(sHeaderName, sHeaderValue);
       }
   }
 }
示例#23
0
 public static List<DataVal> getConnectionHeader(HttpURLConnection h) {
   if (h != null) {
     List<DataVal> pData = new ArrayList<DataVal>();
     Set<Entry<String, List<String>>> pHeaderFields = h.getHeaderFields().entrySet();
     for (Entry<String, List<String>> x : pHeaderFields) {
       // System.out.println("Name : " + x.getKey() + " , Value : " + x.getValue());
       pData.add(new DataVal(x.getKey(), ((List<String>) x.getValue()).get(0)));
     }
     return pData;
   }
   return null;
 }
示例#24
0
 protected Map<String, List<String>> httpConnection(String url) {
   Map<String, List<String>> headers = null;
   try {
     URL urlobj = new URL(url);
     HttpURLConnection con = (HttpURLConnection) urlobj.openConnection();
     headers = con.getHeaderFields();
     Log.d("RES", headers.toString());
     return headers;
   } catch (Exception e) {
     Log.e("ERROR", "Error in httpsConnection():" + e.toString());
     return headers;
   }
 }
示例#25
0
 public static void downloadToFile(String link, String fileName) {
   try {
     URL url = new URL(link);
     HttpURLConnection http = (HttpURLConnection) url.openConnection();
     Map<String, List<String>> header = http.getHeaderFields();
     while (isRedirected(header)) {
       link = header.get("Location").get(0);
       url = new URL(link);
       http = (HttpURLConnection) url.openConnection();
       header = http.getHeaderFields();
     }
     InputStream input = http.getInputStream();
     byte[] buffer = new byte[4096];
     int n = -1;
     OutputStream output = new FileOutputStream(new File(fileName));
     while ((n = input.read(buffer)) != -1) {
       output.write(buffer, 0, n);
     }
     output.close();
   } catch (Exception e) {
     logger.info(e.toString());
   }
 }
  @Test
  public void errorResponseThrowsHttpError() throws Exception {
    given(connection.getURL()).willReturn(new URL(URL));
    given(connection.getResponseCode()).willReturn(400);
    Map<String, List<String>> responseHeaderFields = new LinkedHashMap<String, List<String>>();
    given(connection.getHeaderFields())
        .willReturn(responseHeaderFields, Collections.<String, List<String>>emptyMap());

    Request request = new Request("GET", URL, Collections.<Header>emptyList(), null);

    Response response = underTest.execute(request);

    assertThat(response.getStatus()).isEqualTo(400);
  }
示例#27
0
  @Override
  public InputStream getContent() throws IOException {
    InputStream in;

    try {
      successful = true;
      in = connection.getInputStream();
    } catch (IOException e) {
      successful = false;
      in = connection.getErrorStream();
      if (in == null) {
        throw e;
      }
    }

    String encoding = connection.getHeaderField("Content-Encoding");

    if (config.getMaxResponseSize() > 0) {
      in = new LimitingInputStream(config.getMaxResponseSize(), in);
    }

    if ("gzip".equals(encoding)) {
      in = new GZIPInputStream(in);
    }

    if (config.hasMessageHandlers() || config.isTraceMessage()) {
      byte[] bytes = FileUtil.toBytes(in);
      in = new ByteArrayInputStream(bytes);

      if (config.hasMessageHandlers()) {
        Iterator<MessageHandler> it = config.getMessagerHandlers();
        while (it.hasNext()) {
          MessageHandler handler = it.next();
          if (handler instanceof MessageHandlerWithHeaders) {
            ((MessageHandlerWithHeaders) handler)
                .handleResponse(url, bytes, connection.getHeaderFields());
          } else {
            handler.handleResponse(url, bytes);
          }
        }
      }

      if (config.isTraceMessage()) {
        new TeeInputStream(config, bytes);
      }
    }

    return in;
  }
示例#28
0
 /**
  * XMLファイルを適当なメソッドで送信する。
  *
  * @param String URL
  * @param String XML
  * @param String メソッド(PUT,DELETE)
  * @return InputStream 処理結果を返すInputStream
  */
 public InputStream httpPostXmlWithMethod(String url, String xml, String method) {
   mHttpSucceeded = false;
   try {
     while (url != null) {
       URL u = new URL(url);
       // URLを指定してコネクションを開く
       HttpURLConnection httpConnection = (HttpURLConnection) u.openConnection();
       // メソッドはPOSTを使用する。
       httpConnection.setRequestMethod("POST");
       // GData-Versionは2を指定する
       httpConnection.setRequestProperty("GData-Version", "2");
       if (method != null) {
         // POST以外のメソッドを指定された時は、ヘッダにIf-Match:*とX-HTTP-Method-Overrideを指定
         httpConnection.setRequestProperty("If-Match", "*");
         httpConnection.setRequestProperty("X-HTTP-Method-Override", method);
       }
       // コンテンツを出力する設定
       httpConnection.setDoOutput(true);
       // Content-Typeは XMLファイル
       httpConnection.setRequestProperty("Content-Type", "application/atom+xml");
       // OutputStreamWriterに引数のXMLを設定して出力
       OutputStreamWriter outputStreamWriter =
           new OutputStreamWriter(httpConnection.getOutputStream(), "UTF-8");
       outputStreamWriter.write(xml);
       outputStreamWriter.close();
       // HTTPレスポンスコードを取得
       int responseCode = httpConnection.getResponseCode();
       url = null;
       if (responseCode == HttpURLConnection.HTTP_OK
           || responseCode == HttpURLConnection.HTTP_CREATED) {
         // レスポンスコードがOKまたはCREATEDの場合は処理が完了
         mHttpSucceeded = true;
         // 入力のInputStreamを返して終了
         return httpConnection.getInputStream();
       } else if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
         // レスポンスコードがMOVED_TEMPだった場合、リダイレクトなので、
         // ヘッダからLocationヘッダを取り出して、URLに指定して再実行(先頭のwhileに戻る)
         Map<String, List<String>> responseHeaders = httpConnection.getHeaderFields();
         if (responseHeaders.containsKey("Location")) {
           url = responseHeaders.get("Location").get(0);
         } else if (responseHeaders.containsKey("location")) {
           url = responseHeaders.get("location").get(0);
         }
       }
     }
   } catch (Exception e) {
   }
   return null;
 }
  protected void copyResponseHeaders(HttpServletResponse response, HttpURLConnection connection) {

    Map<String, List<String>> headers = connection.getHeaderFields();
    for (String name : headers.keySet()) {
      List<String> values = headers.get(name);

      for (int i = 0; i < values.size(); i++) {
        String value = values.get(i);
        if (name == null || value == null) {
          continue;
        }
        response.addHeader(name, value);
      }
    }
  }
示例#30
0
  public HttpClientResponse request(String method, String path, Map<String, String> headers) {
    URL url;
    try {
      url = new URL(baseUrl, path);
    } catch (MalformedURLException e) {
      throw new ElasticSearchException("Cannot parse " + path, e);
    }

    HttpURLConnection urlConnection;
    try {
      urlConnection = (HttpURLConnection) url.openConnection();
      urlConnection.setRequestMethod(method);
      if (headers != null) {
        for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
          urlConnection.setRequestProperty(headerEntry.getKey(), headerEntry.getValue());
        }
      }
      urlConnection.connect();
    } catch (IOException e) {
      throw new ElasticSearchException("", e);
    }

    int errorCode = -1;
    Map<String, List<String>> respHeaders = null;
    try {
      errorCode = urlConnection.getResponseCode();
      respHeaders = urlConnection.getHeaderFields();
      InputStream inputStream = urlConnection.getInputStream();
      String body = null;
      try {
        body = Streams.copyToString(new InputStreamReader(inputStream));
      } catch (IOException e1) {
        throw new ElasticSearchException("problem reading error stream", e1);
      }
      return new HttpClientResponse(body, errorCode, respHeaders, null);
    } catch (IOException e) {
      InputStream errStream = urlConnection.getErrorStream();
      String body = null;
      try {
        body = Streams.copyToString(new InputStreamReader(errStream));
      } catch (IOException e1) {
        throw new ElasticSearchException("problem reading error stream", e1);
      }
      return new HttpClientResponse(body, errorCode, respHeaders, e);
    } finally {
      urlConnection.disconnect();
    }
  }