import org.apache.http.HttpEntity;
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;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
public class HttpPostRequestDemo {
public static void main(String[] args) throws IOException {
String url = "https://applets-dev.miyapay.com/api/unioncenter/web-background/account/login";
// HttpGet get = new HttpGet(url);
CloseableHttpClient hc = HttpClients.createDefault();
// ------------------------------------------
//建立body
// 外層使用HashMap的方式傳參
HashMap<String,String> bodyMap = new HashMap<>();
bodyMap.put("userName","admin3");
bodyMap.put("password","123456");
// 請求過程需要使用arraylist的方式傳遞參數,需要進行轉換
ArrayList<NameValuePair> bodyList = new ArrayList<>();
Set<String> keySet = bodyMap.keySet();
for(String key:keySet){
bodyList.add(new BasicNameValuePair(key,bodyMap.get(key)));
}
UrlEncodedFormEntity entityBody = new UrlEncodedFormEntity(bodyList);
// ------------------------------------------
HttpPost post = new HttpPost(url);
post.setEntity(entityBody);
CloseableHttpResponse httpResponse = hc.execute(post);
HttpEntity responseEntity = httpResponse.getEntity();
String response = EntityUtils.toString(responseEntity);
System.out.println(response);
}
}