[Java] 使用HttpURLConnection发送POST请求
使用方法
如下所示。
try {
//コネクション
URL url = new URL("URL");
httpURLConnection_ = (HttpURLConnection) url.openConnection();
httpURLConnection_.setDoOutput(true); //POST可能にする
httpURLConnection_.connect();
//送信したいデータ
String param = "param1=1";
//リクエストボディに送信したいデータを書き込む
OutputStream os = httpURLConnection_.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(param);
writer.flush();
writer.close();
//クローズ処理
os.close();
} catch (IOException e) {
e.printStackTrace();
}
在服务器端获取值时,应按以下方式操作。(服务器继承了HttpServlet的java文件)
public class Server extends HttpServlet{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
request.getParameter("param1");
}
}
印象或想法
表面看起来很难,但实际上比预期的要容易实现。听说它非常有用,所以我想记住它。