本文整理汇总了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);
}
}
示例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;
}
示例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;
}
示例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;
}
示例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();
}
}
示例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测试
}
示例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);
}
}
示例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");
}
}
示例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"
);
}
示例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("%");
}
示例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"
);
}
示例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");
}
示例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");
}
示例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"
);
}
示例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"
);
}