我写了一个接收数据的代码,但我不知道如何将发布数据发送到服务器。
package com.company;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
URL url;
HttpURLConnection conn;
try{
url=new URL("http://mysite/create.php");
String param="name=" + URLEncoder.encode("hello","UTF-8");
conn=(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.close();
String response= "";
Scanner inStream = new Scanner(conn.getInputStream());
while(inStream.hasNextLine())
response+=(inStream.nextLine());
}
catch(MalformedURLException ex){
}
catch(IOException ex){
}
}
}
但执行它时没有反应。我正在运行IntelliJ Jetbrains IDE。