Java Post请求不工作

Java Post请求不工作,java,post,request,Java,Post,Request,为什么这不起作用?我也尝试过使用HttpURLConnection类,但是这也不起作用。php页面找不到发布的数据。 注意:我是用java发布请求的新手 public static String GetURL(String inUrl, String post) { String inputLine = ""; try { if (!inUrl.contains("http")) { throw new Exception("Invalid

为什么这不起作用?我也尝试过使用HttpURLConnection类,但是这也不起作用。php页面找不到发布的数据。 注意:我是用java发布请求的新手

public static String GetURL(String inUrl, String post) {
    String inputLine = "";
    try {
        if (!inUrl.contains("http")) {
            throw new Exception("Invalid URL");
        } else {
            Log.writeLog(inUrl);
            URL url = new URL(inUrl);

            //send post
            URLConnection connection = url.openConnection(); 
            //connection.setRequestMethod("POST"); 
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            connection.connect();

            OutputStream wr = connection.getOutputStream();
            wr.write(post.getBytes());
            wr.flush();
            wr.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            inputLine = in.readLine();
            in.close();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        Log.writeLog("Error getting url.");
    }

    return inputLine;
}

因为你没有指明错误,我很难看出你哪里出错了

然而,我认为使用这样的抽象会容易得多。您的代码如下所示:

URI uri = new URIBuilder()
        .setURI(inUrl)
        .addHeader("Accept-Charset", "UTF-8")
        .addHeader("Content-Type", "application/x-www-form-urlencoded")
        .build();
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(post);
比处理流和连接的低级细节要干净得多