HttpClient in java [closed]

2019-01-17 20:23发布

I want to use a simple HttpClient.

However, it appears sun.net.www.http.HttpClient is unaccessible.

Also, com.ibm.ws.http.HTTPConnection - appears to be more supporting of http server and not client. Why? because when I create an instance of HttpConnection, it has a "getHttpResponse" to which I am supposed to write.

Anyway to use the IBM HttpConnection for HttpClient?

Or, is there any standard httpClient code that I can use?

Thank you.

6条回答
爷的心禁止访问
2楼-- · 2019-01-17 20:52

There is another option in using google-http-java-client.

This library provides a simple and flexible API together with a pluggable approach to use low-level HTTP libraries like java.net.HttpURLConnection or Apache HTTP Client.

Sample code for posting content to content from an InputStream to a specific URL:

HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
InputStream is = ...;
URL url = new URL(...);
String contentType = ...;
HttpRequest httpRequest = requestFactory.buildPostRequest(
  new GenericUrl(url), new InputStreamContent(contentType, is)
);
HttpResponse execute = httpRequest.execute();
查看更多
Lonely孤独者°
3楼-- · 2019-01-17 20:58

Many people use Apache's HTTPClient.

Have a look at the first few chapters of its tutorial to see if it's what you're looking for.

If you're after something simple that's already built into Java, you can look at HttpURLConnection, which you can use to build HTTP requests (example). If you need to do anything more than just simple HTTP requests, though, HTTPClient is probably the way to go.

查看更多
Evening l夕情丶
4楼-- · 2019-01-17 21:08

Try jcabi-http, which acts as a wrapper of JDK HttpURLConnection or Apache HttpClient:

String body = new JdkRequest("http://www.example.com")
  .uri().queryParam("id", "123").back()
  .method(Request.GET)
  .fetch()
  .body();

Check this blog post for more information: http://www.yegor256.com/2014/04/11/jcabi-http-intro.html

查看更多
仙女界的扛把子
5楼-- · 2019-01-17 21:14

I highly recommend Unirest:

Unirest.post("http://httpbin.org/post")
  .queryString("name", "Mark")
  .field("last", "Polo")
  .asString()
查看更多
祖国的老花朵
6楼-- · 2019-01-17 21:15

You don't need a third party class, just use java's own URL and HttpURLConnection classes.
See an example here.

查看更多
看我几分像从前
7楼-- · 2019-01-17 21:16

Try Apache's HTTPClient fluent API it's so easy in use!

// Execute a GET with timeout settings and return response content as String.
Request.Get("http://somehost/")
    .connectTimeout(1000)
    .socketTimeout(1000)
    .execute().returnContent().asString();
查看更多
登录 后发表回答