这里是POST一个例子:
private void sendPost() throws Exception {
String url = "your_url";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
欲了解更多详情,请通过How to send HTTP request GET/POST in Java。
对于所有不赞成的类看看JavaDoc,它会提示用哪个类替换旧代码。例如:
...
*
* @deprecated (4.3) use {@link HttpClientBuilder}. <----- THE HINT IS HERE !
*/
@ThreadSafe
@Deprecated
public class DefaultHttpClient extends AbstractHttpClient {
因此,我会建议使用
HttpClientBuilder.create().build();
由于build()
方法返回一个CloseableHttpClient
是,一个AutoClosable
,您可以将声明在try-与资源语句(Java的7+):
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()){
// use httpClient (no need to close it explicitly)
} catch (IOException e) {
// handle
}
希望它有帮助!