版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/qq_34173549/article/details/80073586
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class DoPOSTParam {
public static void main(String[] args) throws Exception {
// 建立Httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 建立http POST請求
HttpPost httpPost = new HttpPost("http://www.oschina.net/search");
// 設定2個post參數,一個是scope、一個是q
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
parameters.add(new BasicNameValuePair("scope", "project"));
parameters.add(new BasicNameValuePair("q", "java"));
// 構造一個form表單式的實體
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 将請求實體設定到httpPost對象中
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try {
// 執行請求
response = httpclient.execute(httpPost);
// 判斷傳回狀态是否為200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
}
}