當前位置: 首頁>>代碼示例>>Java>>正文


Java Request類代碼示例

本文整理匯總了Java中org.apache.http.client.fluent.Request的典型用法代碼示例。如果您正苦於以下問題:Java Request類的具體用法?Java Request怎麽用?Java Request使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Request類屬於org.apache.http.client.fluent包,在下文中一共展示了Request類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: execute

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
private <U> U execute(URISupplier<URI> uriSupplier, MappingFunction<byte[], U> responseMapper, Supplier<U> notFoundMapper) {
    try {
        URI uri = uriSupplier.get();
        Request request = Request.Get(uri);
        HttpResponse response = request.execute().returnResponse();

        if (response.getStatusLine().getStatusCode() == 200) {
            byte[] returnJson = EntityUtils.toByteArray(response.getEntity());

            return responseMapper.apply(returnJson);


        } else if (response.getStatusLine().getStatusCode() == 404) {
            return notFoundMapper.get();
        } else if (response.getStatusLine().getStatusCode() == 400) {
            throw new IllegalArgumentException("Bad Request");
        } else {
            throw new QueryExecutionException("Something went wrong, status code: " + response.getStatusLine().getStatusCode());
        }


    } catch (URISyntaxException | IOException e) {
        throw new ConnectionException("Error creating connection", e);
    }

}
 
開發者ID:ftrossbach,項目名稱:kiqr,代碼行數:27,代碼來源:GenericBlockingRestKiqrClientImpl.java

示例2: getFile

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
/**
 * 下載文件
 *
 * @param url URL
 * @return 文件的二進製流,客戶端使用outputStream輸出為文件
 */
public static byte[] getFile(String url) {
	try {
		Request request = Request.Get(url);
		HttpEntity resEntity = request.execute().returnResponse().getEntity();
		return EntityUtils.toByteArray(resEntity);
	} catch (Exception e) {
		logger.error("postFile請求異常," + e.getMessage() + "\n post url:" + url);
		e.printStackTrace();
	}
	return null;
}
 
開發者ID:funtl,項目名稱:framework,代碼行數:18,代碼來源:HttpUtils.java

示例3: put

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
/**
 * Send PUT request with authorization header
 * @param url - The url of the POST request
 * @param auth - String for authorization header
 * @param putData - The body of the PUT
 */
public Response put(String url, String auth, JsonJavaObject putData) throws URISyntaxException, IOException, JsonException {
	URI normUri = new URI(url).normalize();
	Request putRequest = Request.Put(normUri);
	
	//Add auth header
	if(StringUtil.isNotEmpty(auth)) {
		putRequest.addHeader("Authorization", auth);
	}
	
	//Add put data
	String putDataString = JsonGenerator.toJson(JsonJavaFactory.instanceEx, putData);
	if(putData != null) {
		putRequest = putRequest.bodyString(putDataString, ContentType.APPLICATION_JSON);
	}
	
	Response response = executor.execute(putRequest);
	return response;
}
 
開發者ID:OpenNTF,項目名稱:XPages-Fusion-Application,代碼行數:25,代碼來源:RestUtil.java

示例4: post

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
/**
 * post 請求
 *
 * @param url
 * @param xml
 * @return
 */
private static String post(String url, String xml) {
	try {
		HttpEntity entity = Request.Post(url).bodyString(xml, ContentType.create("text/xml", Consts.UTF_8.name())).execute().returnResponse().getEntity();
		if (entity != null) {
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			entity.writeTo(byteArrayOutputStream);
			return byteArrayOutputStream.toString(Consts.UTF_8.name());
		}
		return null;
	} catch (Exception e) {
		logger.error("post請求異常," + e.getMessage() + "\npost url:" + url);
		e.printStackTrace();
	}
	return null;
}
 
開發者ID:funtl,項目名稱:framework,代碼行數:23,代碼來源:PayManager.java

示例5: loadMetadata

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
private void loadMetadata() {
    String requestUrl = "http://archive.org/metadata/" + identifier;

    try {
        // get the metadata for the item as a json stream
        InputStream jsonStream = Request.Get(requestUrl).execute().returnContent().asStream();

        BufferedReader streamReader = new BufferedReader(new InputStreamReader(jsonStream));

        StringBuilder result = new StringBuilder();
        String line;

        // read each line of the stream
        while ((line = streamReader.readLine()) != null) {
            result.append(line);
        }
        streamReader.close();

        JsonReader jsonReader = Json.createReader(new StringReader(result.toString()));
        metadata = jsonReader.readObject();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
開發者ID:zacwood9,項目名稱:attics,代碼行數:25,代碼來源:Item.java

示例6: main

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
public static void main(String[] args) throws Exception {

        // URL白名單組件測試
        CheckURL urlCheck = new CheckURL();
        String[] urlWList = {"joychou.com", "joychou.me"};
        Boolean ret = urlCheck.checkUrlWlist("http://test.joychou.org", urlWList);
        System.out.println(ret);

        // SSRF組件測試
        SSRF check = new SSRF();
        String url = "http://127.0.0.1.xip.io";
        ret = check.checkSSRF(url);
        if (ret){
            String con = Request.Get(url).execute().returnContent().toString();
            System.out.println(con);
        }
        else {
            System.out.println("Bad boy. The url is illegal");
        }

        // 獲取客戶端IP測試


    }
 
開發者ID:JoyChou93,項目名稱:trident,代碼行數:25,代碼來源:Test.java

示例7: doRequest

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
private static void doRequest(final String uri, final String sign) {
	System.out.println("--- Signature: " + sign);
	try {
		final Request req = Request.Get(uri).connectTimeout(5000).socketTimeout(5000);
		if (sign != null) {
			req.setHeader(SimpleAuth.HTTP_HEADER, SimpleAuth.SCHEME + " " + sign);
		}
		final HttpResponse res = req.execute().returnResponse();
		final String status = String.valueOf(res.getStatusLine());
		final String body = EntityUtils.toString(res.getEntity()).trim();
		System.out.println("head> " + status);  // HTTP Status
		System.out.println("body> " + body);    // Body
	} catch (IOException e) {
		System.out.println("Unable to connect: " + e);
	}
}
 
開發者ID:ggrandes,項目名稱:simpleauth,代碼行數:17,代碼來源:ExampleHttpFluent.java

示例8: addHeadersToRequest

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
@VisibleForTesting
void addHeadersToRequest(final Request request, final URL trackerAnnounceURI) {
    final int port = trackerAnnounceURI.getPort();
    // Add Host header first to prevent Request appending it at the end
    request.addHeader("Host", trackerAnnounceURI.getHost() + (port == -1 ? "" : ":" + port));

    //noinspection SimplifyStreamApiCallChains
    this.headers.stream().forEachOrdered(header -> {
        final String name = header.getKey();
        final String value = header.getValue()
                .replaceAll("\\{java}", System.getProperty("java.version"))
                .replaceAll("\\{os}", System.getProperty("os.name"))
                .replaceAll("\\{locale}", Locale.getDefault().toLanguageTag());

        request.addHeader(name, value);
    });

    // if Connection header was not set, we append it. Apache HttpClient will add it what so ever, so prefer "Close" over "keep-alive"
    final boolean hasConnectionHeader = this.headers.stream()
            .anyMatch(header -> "Connection".equalsIgnoreCase(header.getKey()));
    if (!hasConnectionHeader) {
        request.addHeader("Connection", "Close");
    }
}
 
開發者ID:anthonyraymond,項目名稱:joal,代碼行數:25,代碼來源:BitTorrentClient.java

示例9: shouldReplaceInfoHash

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
@Test
public void shouldReplaceInfoHash() throws MalformedURLException, UnsupportedEncodingException {
    final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address());
    final TorrentWithStats torrent = TorrentWithStatsTest.createMocked();
    final BitTorrentClient client = new BitTorrentClient(
            defaultPeerIdGenerator,
            defaultKeyGenerator,
            defaultUrlEncoder,
            "info_hash={infohash}",
            Collections.emptyList(),
            defaultNumwantProvider
    );


    final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler);

    assertThat(request.toString())
            .isEqualTo(
                    computeExpectedURLBegin(defaultTrackerURL) +
                            "info_hash=" + defaultUrlEncoder.encode(new String(torrent.getTorrent().getInfoHash(), Torrent.BYTE_ENCODING)) +
                            " HTTP/1.1"
            );
}
 
開發者ID:anthonyraymond,項目名稱:joal,代碼行數:24,代碼來源:BitTorrentClientUrlBuilderTest.java

示例10: shouldUrlEncodeInfoHash

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
@Test
public void shouldUrlEncodeInfoHash() throws UnsupportedEncodingException {
    final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address());
    final TorrentWithStats torrent = TorrentWithStatsTest.createMocked();
    final BitTorrentClient client = new BitTorrentClient(
            defaultPeerIdGenerator,
            defaultKeyGenerator,
            new UrlEncoder("", Casing.LOWER),
            "info_hash={infohash}",
            Collections.emptyList(),
            defaultNumwantProvider
    );


    final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler);

    assertThat(request.toString())
            .contains("%");
}
 
開發者ID:anthonyraymond,項目名稱:joal,代碼行數:20,代碼來源:BitTorrentClientUrlBuilderTest.java

示例11: shouldReplacePeerId

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
@Test
public void shouldReplacePeerId() throws MalformedURLException, UnsupportedEncodingException {
    final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address());
    final TorrentWithStats torrent = TorrentWithStatsTest.createMocked();
    final BitTorrentClient client = new BitTorrentClient(
            defaultPeerIdGenerator,
            defaultKeyGenerator,
            defaultUrlEncoder,
            "peer_id={peerid}",
            Collections.emptyList(),
            defaultNumwantProvider
    );


    final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler);

    assertThat(request.toString())
            .isEqualTo(
                    computeExpectedURLBegin(defaultTrackerURL) +
                            "peer_id=" + defaultPeerIdGenerator.getPeerId(torrent.getTorrent(), RequestEvent.STARTED) +
                            " HTTP/1.1"
            );
}
 
開發者ID:anthonyraymond,項目名稱:joal,代碼行數:24,代碼來源:BitTorrentClientUrlBuilderTest.java

示例12: shouldUrlEncodePeerId

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
@Test
public void shouldUrlEncodePeerId() throws UnsupportedEncodingException {
    final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address());
    final TorrentWithStats torrent = TorrentWithStatsTest.createMocked();
    final BitTorrentClient client = new BitTorrentClient(
            PeerIdGeneratorTest.createForPattern("-AA-[a]{16}", true),
            defaultKeyGenerator,
            new UrlEncoder("", Casing.LOWER),
            "peer_id={peerid}",
            Collections.emptyList(),
            defaultNumwantProvider
    );


    final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler);

    assertThat(request.toString())
            .contains("%61%61%61%61%61%61%61%61%61%61%61%61%61%61%61%61");
}
 
開發者ID:anthonyraymond,項目名稱:joal,代碼行數:20,代碼來源:BitTorrentClientUrlBuilderTest.java

示例13: shouldNotUrlEncodePeerId

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
@Test
public void shouldNotUrlEncodePeerId() throws UnsupportedEncodingException {
    final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address());
    final TorrentWithStats torrent = TorrentWithStatsTest.createMocked();
    final BitTorrentClient client = new BitTorrentClient(
            PeerIdGeneratorTest.createForPattern("-AA-[a]{16}", false),
            defaultKeyGenerator,
            new UrlEncoder("", Casing.LOWER),
            "peer_id={peerid}",
            Collections.emptyList(),
            defaultNumwantProvider
    );

    final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler);

    assertThat(request.toString())
            .contains("aaaaaaaaaaaaaaaa");
}
 
開發者ID:anthonyraymond,項目名稱:joal,代碼行數:19,代碼來源:BitTorrentClientUrlBuilderTest.java

示例14: shouldReplaceUploaded

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
@Test
public void shouldReplaceUploaded() throws MalformedURLException, UnsupportedEncodingException {
    final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address());
    final TorrentWithStats torrent = TorrentWithStatsTest.createMocked();
    final BitTorrentClient client = new BitTorrentClient(
            defaultPeerIdGenerator,
            defaultKeyGenerator,
            defaultUrlEncoder,
            "uploaded={uploaded}",
            Collections.emptyList(),
            defaultNumwantProvider
    );


    final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler);

    assertThat(request.toString())
            .isEqualTo(
                    computeExpectedURLBegin(defaultTrackerURL) +
                            "uploaded=" + torrent.getUploaded() +
                            " HTTP/1.1"
            );
}
 
開發者ID:anthonyraymond,項目名稱:joal,代碼行數:24,代碼來源:BitTorrentClientUrlBuilderTest.java

示例15: shouldReplaceDownloaded

import org.apache.http.client.fluent.Request; //導入依賴的package包/類
@Test
public void shouldReplaceDownloaded() throws MalformedURLException, UnsupportedEncodingException {
    final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address());
    final TorrentWithStats torrent = TorrentWithStatsTest.createMocked();
    final BitTorrentClient client = new BitTorrentClient(
            defaultPeerIdGenerator,
            defaultKeyGenerator,
            defaultUrlEncoder,
            "downloaded={downloaded}",
            Collections.emptyList(),
            defaultNumwantProvider
    );


    final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler);

    assertThat(request.toString())
            .isEqualTo(
                    computeExpectedURLBegin(defaultTrackerURL) +
                            "downloaded=" + torrent.getDownloaded() +
                            " HTTP/1.1"
            );
}
 
開發者ID:anthonyraymond,項目名稱:joal,代碼行數:24,代碼來源:BitTorrentClientUrlBuilderTest.java


注:本文中的org.apache.http.client.fluent.Request類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。