我想创建一个函数,发送带有JSON
数据的帖子请求
我想做点什么:
public Service() throws Exception {
CommunicationService c = new CommunicationService();
List<String> list = new ArrayList<String>();
list.add("email");
list.add("test@email.com");
list.add("password");
list.add("testPassword");
c.post("https://discordapp.com/api/auth/login", list);
}
通讯服务类
public class CommunicationService {
public void post(String url, List<String> params) {
// WHAT I ASK YOU
// I want to do the post request on URL
for (int i = 0; i < params.size(); i++)
{
// params name in i index from list and value in i + 1
i++;
}
}
}
答案 0 :(得分:0)
public static void saveToUrl(String myURL, List<MyObject> myParams) throws IOException
{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(myURL);
List<MyObject> params = myParams;
params.add(new BasicNameValuePair("task", "savemodel"));
params.add(new BasicNameValuePair("code", generatedJSONString));
CloseableHttpResponse response = null;
Scanner in = null;
try
{
post.setEntity(new UrlEncodedFormEntity(params));
response = httpClient.execute(post);
// System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
in = new Scanner(entity.getContent());
while (in.hasNext())
{
System.out.println(in.next());
}
EntityUtils.consume(entity);
} finally
{
in.close();
response.close();
}
}