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); } }
/** * Make a GET-request to the devRant server. * * @param url The url to make the request to. * @return A {@link JsonObject} containing the response. */ JsonObject get(String url, NameValuePair... params) { StringBuilder finalUrl = new StringBuilder(url).append('?'); List<NameValuePair> paramList = getParameters(params); // Add all parameters. try { for (NameValuePair param : paramList) finalUrl.append('&').append(param.getName()).append('=').append(URLEncoder.encode(param.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { // This never happens. LOGGER.error("Unsupported encoding while trying to encode parameter value.", e); } return executeRequest(Request.Get(BASE_URL + finalUrl.toString())); }
/** * 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; }
/** * 下载文件 * * @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; }
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(); } }
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测试 }
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); } }
@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"); } }
@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" ); }
@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("%"); }
@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" ); }
@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"); }
@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"); }
@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" ); }
@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" ); }
@Test public void shouldReplaceLeft() throws MalformedURLException, UnsupportedEncodingException { final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address()); final TorrentWithStats torrent = TorrentWithStatsTest.createMocked(); final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, defaultUrlEncoder, "left={left}", Collections.emptyList(), defaultNumwantProvider ); final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler); assertThat(request.toString()) .isEqualTo( computeExpectedURLBegin(defaultTrackerURL) + "left=" + torrent.getLeft() + " HTTP/1.1" ); }
@Test public void shouldReplacePort() throws MalformedURLException, UnsupportedEncodingException { final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address()); final TorrentWithStats torrent = TorrentWithStatsTest.createMocked(); final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, defaultUrlEncoder, "port={port}", Collections.emptyList(), defaultNumwantProvider ); final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler); assertThat(request.toString()) .isEqualTo( computeExpectedURLBegin(defaultTrackerURL) + "port=" + connHandler.getPort() + " HTTP/1.1" ); }
@Test public void shouldReplaceIpv6AndRemoveIpv4() throws MalformedURLException, UnsupportedEncodingException { final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet6Address()); final TorrentWithStats torrent = TorrentWithStatsTest.createMocked(); final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, new UrlEncoder("[0-9a-zA-Z]", Casing.LOWER), "ipv6={ipv6}&ip={ip}", Collections.emptyList(), defaultNumwantProvider ); final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler); assertThat(request.toString()) .isEqualTo(computeExpectedURLBegin(defaultTrackerURL) + "ipv6=" + connHandler.getIpAddress().getHostAddress().replaceAll(":", "%3a") + " HTTP/1.1" ); }
@Test public void shouldReplaceIpv4AndRemoveIpv6() throws MalformedURLException, UnsupportedEncodingException { final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address()); final TorrentWithStats torrent = TorrentWithStatsTest.createMocked(); final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, defaultUrlEncoder, "ip={ip}&ipv6={ipv6}", Collections.emptyList(), defaultNumwantProvider ); final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler); assertThat(request.toString()) .isEqualTo( computeExpectedURLBegin(defaultTrackerURL) + "ip=" + connHandler.getIpAddress().getHostAddress() + " HTTP/1.1" ); }
@Test public void shouldReplaceEvent() throws MalformedURLException, UnsupportedEncodingException { final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address()); final TorrentWithStats torrent = TorrentWithStatsTest.createMocked(); final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, defaultUrlEncoder, "event={event}", Collections.emptyList(), defaultNumwantProvider ); final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler); assertThat(request.toString()) .isEqualTo( computeExpectedURLBegin(defaultTrackerURL) + "event=" + RequestEvent.STARTED.getEventName() + " HTTP/1.1" ); }
@Test public void shouldReplaceKey() throws MalformedURLException, UnsupportedEncodingException { final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address()); final TorrentWithStats torrent = TorrentWithStatsTest.createMocked(); final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, defaultUrlEncoder, "key={key}", Collections.emptyList(), defaultNumwantProvider ); final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler); assertThat(request.toString()) .isEqualTo( computeExpectedURLBegin(defaultTrackerURL) + "key=" + defaultKeyGenerator.getKey(torrent.getTorrent(), RequestEvent.STARTED) + " HTTP/1.1" ); }
@Test public void shouldReplaceNumWant() throws MalformedURLException, UnsupportedEncodingException { final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address()); final TorrentWithStats torrent = TorrentWithStatsTest.createMocked(); final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, defaultUrlEncoder, "numwant={numwant}", Collections.emptyList(), defaultNumwantProvider ); final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STARTED, torrent, connHandler); assertThat(request.toString()) .isEqualTo( computeExpectedURLBegin(defaultTrackerURL) + "numwant=" + defaultNumwantProvider.get(RequestEvent.STARTED) + " HTTP/1.1" ); }
@Test public void shouldReplaceNumWantWithNumwantOnStopValue() throws MalformedURLException, UnsupportedEncodingException { final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address()); final TorrentWithStats torrent = TorrentWithStatsTest.createMocked(); final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, defaultUrlEncoder, "numwant={numwant}", Collections.emptyList(), defaultNumwantProvider ); final Request request = client.buildAnnounceRequest(defaultTrackerURL, RequestEvent.STOPPED, torrent, connHandler); assertThat(request.toString()) .isEqualTo( computeExpectedURLBegin(defaultTrackerURL) + "numwant=" + defaultNumwantProvider.get(RequestEvent.STOPPED) + " HTTP/1.1" ); }
@Test public void shouldReturnURLEvenIfBaseUrlContainsParams() throws UnsupportedEncodingException, MalformedURLException { final ConnectionHandler connHandler = createMockedConnectionHandler(createMockedINet4Address()); final TorrentWithStats torrent = TorrentWithStatsTest.createMocked(); final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, defaultUrlEncoder, "event={event}", Collections.emptyList(), defaultNumwantProvider ); final URL trackerURL = new URL("http://my.tracker.com/announce?name=jack"); final Request request = client.buildAnnounceRequest(trackerURL, RequestEvent.STARTED, torrent, connHandler); assertThat(request.toString()).startsWith("GET " + trackerURL.toString()) .isEqualTo( computeExpectedURLBegin(trackerURL).replaceAll("\\?$", "") + "&event=" + RequestEvent.STARTED.getEventName() + " HTTP/1.1" ).contains("?name=jack"); }
@Test public void shouldAddHeaders() { final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, defaultUrlEncoder, "d", Lists.newArrayList(new HttpHeader("HName", "HValue"), new HttpHeader("Accept", "*/*")), defaultNumwantProvider ); final Request request = Mockito.mock(Request.class); client.addHeadersToRequest(request, defaultTrackerURL); Mockito.verify(request, Mockito.times(1)).addHeader("HName", "HValue"); Mockito.verify(request, Mockito.times(1)).addHeader("Accept", "*/*"); }
@Test public void shouldAddConnectionHeaderIfNotPresent() { final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, defaultUrlEncoder, "d", Lists.newArrayList(), defaultNumwantProvider ); final Request request = Mockito.mock(Request.class); client.addHeadersToRequest(request, defaultTrackerURL); Mockito.verify(request, Mockito.times(1)).addHeader("Connection", "Close"); }
@Test public void shouldNotOverrideHeaderIfPresent() { final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, defaultUrlEncoder, "d", Lists.newArrayList(new HttpHeader("Connection", "WOAW")), defaultNumwantProvider ); final Request request = Mockito.mock(Request.class); client.addHeadersToRequest(request, defaultTrackerURL); Mockito.verify(request, Mockito.times(1)).addHeader("Connection", "WOAW"); }
@Test public void shouldAddHostHeader() throws MalformedURLException { final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, defaultUrlEncoder, "d", Lists.newArrayList(new HttpHeader("Connection", "WOAW")), defaultNumwantProvider ); final Request requestWithoutPort = Mockito.mock(Request.class); final URL urlWithoutPort = new URL("http://my.tracker.com"); client.addHeadersToRequest(requestWithoutPort, urlWithoutPort); Mockito.verify(requestWithoutPort, Mockito.times(1)).addHeader("Host", urlWithoutPort.getHost()); final Request requestWithPort = Mockito.mock(Request.class); final URL urlWithPort = new URL("http://my.tracker.com:1234"); client.addHeadersToRequest(requestWithPort, urlWithPort); Mockito.verify(requestWithPort, Mockito.times(1)).addHeader("Host", urlWithPort.getHost() + ":" + urlWithPort.getPort()); }
@Test public void shouldReplacePlaceholderInHeaders() throws URISyntaxException { final BitTorrentClient client = new BitTorrentClient( defaultPeerIdGenerator, defaultKeyGenerator, defaultUrlEncoder, "d", Lists.newArrayList( new HttpHeader("javaOnly", "{java}"), new HttpHeader("osOnly", "{os}"), new HttpHeader("javaWithText", "Java v{java} qsdqd"), new HttpHeader("osWithText", "Os {os} qdqsdqsd") ), defaultNumwantProvider ); final Request request = Mockito.mock(Request.class); client.addHeadersToRequest(request, defaultTrackerURL); Mockito.verify(request, Mockito.times(1)).addHeader("javaOnly", System.getProperty("java.version")); Mockito.verify(request, Mockito.times(1)).addHeader("osOnly", System.getProperty("os.name")); Mockito.verify(request, Mockito.times(1)).addHeader("javaWithText", "Java v" + System.getProperty("java.version") + " qsdqd"); Mockito.verify(request, Mockito.times(1)).addHeader("osWithText", "Os " + System.getProperty("os.name") + " qdqsdqsd"); }
@Override public List<EmbeddableData> getList() throws IOException { if (this.token == null) throw new IllegalArgumentException("Client not authenticated"); final Gson gson = new GsonBuilder().create(); final String response = Request.Get(this.apiHost.toString() + "/dati-gov/v1/dashboard/iframes") .setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token.getId()) .setHeader(HttpHeaders.ACCEPT, "application/json") .execute().returnContent().asString(); return gson.fromJson( response, new TypeToken<List<EmbeddableData>>() { }.getType() ); }
public HTMLCommentReporter(String aURL) { String pageBody =""; try { pageBody = Request.Get(aURL) .execute().returnContent().asString(); } catch (IOException e) { e.printStackTrace(); } //String pageBody = get(aURL).andReturn().getBody().asString(); comments = new HTMLCommentFinder(pageBody); comments.findAllComments(); }
/** * Uploads the given HistoryRecord to the search index service * * @param record HistoryRecord to send to index. Should have a body. */ public void index(HistoryRecord record) { try { if (record.getBody() != null) { String url = baseUrl + "/collections/" + collection + "/" + URLEncoder.encode(record.getUrl(), Charsets.UTF_8.name()); if (record.getTimestamp() != null) { url = url + "/" + URLEncoder.encode(record.getTimestamp(), Charsets.UTF_8.name()); } Request.Post(url).bodyString(record.getBody(), ContentType.TEXT_HTML).execute(); } } catch (IOException e) { e.printStackTrace(); } }
public static String post(String location, String jsonArgs) { Content result = null; try { StringEntity jsonEntity = new StringEntity(jsonArgs); result = Request.Post(location) .body(jsonEntity) .execute() .returnContent(); } catch (IOException e) { e.printStackTrace(); } return (result == null) ? null : result.toString(); }
/** * Build a request. * * @param endpoint The endpoint to make the request to. * @param requestFunction The function to create a new request from a URI. * @param params The request parameters. * @return A request. */ private Request buildRequest(String endpoint, Function<URI, Request> requestFunction, List<NameValuePair> params) { URI uri; try { // Build the URI. uri = new URIBuilder(resolve(endpoint)) .addParameters(params) .build(); } catch (URISyntaxException e) { // This never happens. throw new IllegalArgumentException("Could not build URI.", e); } return requestFunction.apply(uri) .connectTimeout(timeout) .socketTimeout(timeout); }
/** * Creates a web hook in Gogs with the passed json configuration string * * @param jsonCommand A json buffer with the creation command of the web hook * @param projectName the project (owned by the user) where the webHook should be created * @throws IOException something went wrong */ int createWebHook(String jsonCommand, String projectName) throws IOException { String gogsHooksConfigUrl = getGogsServer_apiUrl() + "repos/" + this.gogsServer_user + "/" + projectName + "/hooks"; Executor executor = getExecutor(); String result = executor .execute(Request.Post(gogsHooksConfigUrl).bodyString(jsonCommand, ContentType.APPLICATION_JSON)) .returnContent().asString(); JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( result ); int id = jsonObject.getInt("id"); return id; }
/** * Removes a web hook from a GOGS project * * @param projectName Name of the Gogs project to remove the hook from * @param hookId The ID of the hook to remove * @throws IOException something went wrong */ void removeHook(String projectName, int hookId) throws IOException { String gogsHooksConfigUrl = getGogsServer_apiUrl() + "repos/" + this.gogsServer_user + "/" + projectName + "/hooks/" + hookId; Executor executor = getExecutor(); int result = executor .execute(Request.Delete(gogsHooksConfigUrl)) .returnResponse().getStatusLine().getStatusCode(); if (result != 204) { throw new IOException("Delete hook did not return the expected value (returned " + result + ")"); } }
private void post() throws IOException { //以Http/1.1版本协议执行一个POST请求,同时配置Expect-continue handshake达到性能调优, //请求中包含String类型的请求体并将响应内容作为byte[]返回 Request.Post("http://blog.csdn.net/vector_yi") .useExpectContinue() .version(HttpVersion.HTTP_1_1) .bodyString("Important stuff", ContentType.DEFAULT_TEXT) .execute().returnContent().asBytes(); //通过代理执行一个POST请求并添加一个自定义的头部属性,请求包含一个HTML表单类型的请求体 //将返回的响应内容存入文件 Request.Post("http://blog.csdn.net/vector_yi") .addHeader("X-Custom-header", "stuff") .viaProxy(new HttpHost("myproxy", 8080)) .bodyForm(Form.form().add("username", "vip").add("password", "secret").build()) .execute().saveContent(new File("result.dump")); Request.Post("http://targethost/login") .bodyForm(Form.form().add("username", "vip").add("password", "secret").build()) .execute().returnContent(); }
/** * Send POST request with authorization header and additional headers * @param url - The url of the POST request * @param auth - String for authorization header * @param headers - Hashmap of headers to add to the request * @param postData - The body of the POST * @return the Response to the POST request */ public Response post(String url, String auth, HashMap<String, String> headers, JsonJavaObject postData) throws JsonException, IOException, URISyntaxException { URI normUri = new URI(url).normalize(); Request postRequest = Request.Post(normUri); //Add all headers if(StringUtil.isNotEmpty(auth)) { postRequest.addHeader("Authorization", auth); } if(headers != null && headers.size() > 0){ for (Map.Entry<String, String> entry : headers.entrySet()) { postRequest.addHeader(entry.getKey(), entry.getValue()); } } String postDataString = JsonGenerator.toJson(JsonJavaFactory.instanceEx, postData); Response response = executor.execute(postRequest.bodyString(postDataString, ContentType.APPLICATION_JSON)); return response; }
public Response post(String url, String auth, JsonJavaObject postData, File fileUpload) throws JsonException, IOException, URISyntaxException { URI normUri = new URI(url).normalize(); Request postRequest = Request.Post(normUri); //Add all headers if(StringUtil.isNotEmpty(auth)) { postRequest.addHeader("Authorization", auth); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("images_file", fileUpload, ContentType.APPLICATION_OCTET_STREAM, fileUpload.getName()); if(postData != null) { String postDataString = JsonGenerator.toJson(JsonJavaFactory.instanceEx, postData); builder.addTextBody("classifier_ids", postDataString, ContentType.MULTIPART_FORM_DATA); } HttpEntity multipart = builder.build(); postRequest.body(multipart); Response response = executor.execute(postRequest); return response; }
/** * 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; }