HttpClient in java [closed]

2019-01-17 20:45发布

问题:

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.

回答1:

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.



回答2:

I highly recommend Unirest:

Unirest.post("http://httpbin.org/post")
  .queryString("name", "Mark")
  .field("last", "Polo")
  .asString()


回答3:

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



回答4:

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();


回答5:

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



回答6:

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();