Java 如何使用Httpurlconnection将post数据发送到网站
我编写了一个接收数据的代码,但我不知道如何将post数据发送到服务器Java 如何使用Httpurlconnection将post数据发送到网站,java,post,httpurlconnection,Java,Post,Httpurlconnection,我编写了一个接收数据的代码,但我不知道如何将post数据发送到服务器 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.u
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。尝试使用BasicNameValuePair,如中所建议,但namevaluepair是deprecated@amupotiGet去掉
catch(IOException ex){}
和另一个空的catch块,即使没有响应,您也可以找出错误所在。它将响应代码显示为500@artbristolUm,500不是“无响应”,而是内部服务器错误
。在这一点上,如果可能的话,我会和服务器人员核实一下,如果可能的话,我可能会查看一下他们的日志。他们根本不可能不验证他们的输入,并且他们应该输出错误的请求
,尽管(如中所示,您的请求被破坏)。