知识点

相关文章

更多

最近更新

更多

HttpClient PUT请求示例

2019-04-09 22:37|来源: 网路

Maven依赖关系

我们使用maven来管理依赖关系,并使用Apache HttpClient 4.5版本。 将以下依赖项添加到您的项目中,以便创建HTTP PUT请求方法。

pom.xml 文件的内容如下 -

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yiibai.httpclient.httmethods</groupId>
    <artifactId>http-get</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <url>https://memorynotfound.com</url>
    <name>httpclient - ${project.artifactId}</name>

    <dependencies>
        <!-- Apache Commons IO -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


HTTP PUT请求方法示例

在以下示例中,我们将数据发布到资源URL:http://httpbin.org/put 。 该资源确认数据并返回一个JSON对象,我们只需将其打印到控制台。 注意:使用Java7try-with-resources来自动处理关闭ClosableHttpClient。 接下来使用Java 8lambda作为ResponseHandler。 在这里,根据Http状态代码判断返回状态,当一切正常时,我们会将解析的响应正文返回给String。 当状态码不是所期望的时候,将抛出一个ClientProtocolException,表明Http PUT请求方法失败。 最后,我们将响应主体打印到控制台。

文件:HttpPutRequestMethodExample.java -

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;

/**
 * This example demonstrates the use of {@link HttpPut} request method.
 */
public class HttpPutRequestMethodExample {

    public static void main(String... args) throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPut httpPut = new HttpPut("http://httpbin.org/put");
            httpPut.setEntity(new StringEntity("Hello, World"));

            System.out.println("Executing request " + httpPut.getRequestLine());

            // Create a custom response handler
            ResponseHandler<String> responseHandler = response -> {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpPut, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}


执行上面示例代码,得到以下结果 -

Executing request PUT http://httpbin.org/put HTTP/1.1
----------------------------------------
{
  "args": {}, 
  "data": "Hello, World", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept-Encoding": "gzip,deflate", 
    "Connection": "close", 
    "Content-Length": "12", 
    "Content-Type": "text/plain; charset=ISO-8859-1", 
    "Host": "httpbin.org", 
    "User-Agent": "Apache-HttpClient/4.5.5 (Java/1.8.0_65)"
  }, 
  "json": null, 
  "origin": "112.67.166.104", 
  "url": "http://httpbin.org/put"
}

相关问答

更多
  • 异步调用一个简单的方法是jms,比较通用的开源实现是activemq
  • 结帐http://htmlunit.sourceforge.net/ Checkout http://htmlunit.sourceforge.net/
  • 只需在URI中指定HTTPS。 new Uri("https://foobar.com/"); Foobar.com将需要一个受信任的SSL证书,否则您的呼叫将以不可信的错误失败。 编辑答案: 具有HttpClient的ClientCertificates WebRequestHandler handler = new WebRequestHandler(); X509Certificate2 certificate = GetMyX509Certificate(); handler.ClientCert ...
  • 根据MSDN ,因为.NET 4.5以下实例方法是线程安全的 (感谢@ischell): CancelPendingRequests DeleteAsync GetAsync GetByteArrayAsync GetStreamAsync GetStringAsync PostAsync PutAsync SendAsync According to MSDN, since .NET 4.5 The following instance methods are thread safe (thanks @ ...
  • 普遍的共识是你不需要(不应该)处理HttpClient。 许多密切参与其工作方式的人已经说明了这一点。 请参阅Darrel Miller的博客文章和相关的SO文章: HttpClient抓取导致内存泄漏以供参考。 我还强烈建议您阅读“ 使用ASP.NET设计Evolvable Web API”的HttpClient章节,了解引擎盖下的内容,特别是引用的“生命周期”部分: 尽管HttpClient间接地实现了IDisposable接口,但HttpClient的标准用法并不是在每个请求之后处理。 HttpCli ...
  • 您可以使用此代码前进,它适用于我.. URL url = new URL("Your URL"); HttpURLConnection httpsURLConnection = (HttpURLConnection)url.openConnection(); httpsURLConnection.setReadTimeout(15000); httpsURLConnection.setConnectTimeout(20000); httpsURLConnec ...
  • 绝对使用服务,以便您拥有API请求的中心位置。 我通常为每种类型的api提供一项服务,即/ products,/ orders等。我发现(作为例子)来自应用程序周围的组件可能会调用/ products中的端点,因此分离为服务会使代码更清洁。 我将这些服务放在CoreModule https://angular.io/guide/ngmodule-faq#coremodule中 。 以下是如何从服务使用api调用的示例,而不是直接来自组件。 https://www.concretepage.com/angul ...
  • 我只是通过将第一个大写字母改为小写来解决第二种方法的问题。 真的很愚蠢的错误..它被定义为'firstName' ,我写的是它写在DataBase表中。 I've solved the problem of the second method just by changing the first capital letter to lower case. Really stupid error.. It is defined as 'firstName', and I wrote it as it was ...
  • 正如我在评论中提到的,HttpClient和JEditorPane用于获取URL内容的URLConnection不会相互通信。 因此,HttpClient可能获取的任何cookie都不会转移到URLConnection。 但是,您可以像这样子类化JEditorPane: final HttpClient httpClient = new DefaultHttpClient(); /* initialize httpClient and fetch your login page to get the co ...
  • 这只是一个不同的API。 Observable有更好的方法来分离“如何流动”(所有操作符:map,merge,concat等)与执行(.subscribe),这往往有助于获得更好的图片。 Plus提供有用的方法来取消或重试请求,如果失败。 如果你需要Promise API,你可以随时使用Observable.toPromise() (使用async / await,这也很有用) 所以对我来说,这只是表示同一事物的两种方式,每种方式都有其优势,但由于Observable更通用,他们使用了这种方法 - 可以将O ...