Java - 通过 POST 方法轻松发送 HTTP 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4205980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:33:35  来源:igfitidea点击:

Java - sending HTTP parameters via POST method easily

javahttpposthttpurlconnection

提问by dan

I am successfully using this code to send HTTPrequests with some parameters via GETmethod

我成功地使用此代码HTTP通过GET方法发送 带有一些参数的请求

void sendRequest(String request)
{
    // i.e.: request = "http://example.com/index.php?param1=a&param2=b&param3=c";
    URL url = new URL(request); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
    connection.setDoOutput(true); 
    connection.setInstanceFollowRedirects(false); 
    connection.setRequestMethod("GET"); 
    connection.setRequestProperty("Content-Type", "text/plain"); 
    connection.setRequestProperty("charset", "utf-8");
    connection.connect();
}

Now I may need to send the parameters (i.e. param1, param2, param3) via POSTmethod because they are very long. I was thinking to add an extra parameter to that method (i.e. String httpMethod).

现在我可能需要通过POST方法发送参数(即param1、param2、param3),因为它们很长。我正在考虑向该方法添加一个额外的参数(即 String httpMethod)。

How can I change the code above as little as possible to be able to send paramters either via GETor POST?

如何尽可能少地更改上面的代码,以便能够通过GET或发送参数POST

I was hoping that changing

我希望改变

connection.setRequestMethod("GET");

to

connection.setRequestMethod("POST");

would have done the trick, but the parameters are still sent via GET method.

本来可以做到这一点,但参数仍然通过 GET 方法发送。

Has HttpURLConnectiongot any method that would help? Is there any helpful Java construct?

HttpURLConnection什么方法可以帮助吗?是否有任何有用的 Java 构造?

Any help would be very much appreciated.

任何帮助将不胜感激。

采纳答案by Alan Geleynse

In a GET request, the parameters are sent as part of the URL.

在 GET 请求中,参数作为 URL 的一部分发送。

In a POST request, the parameters are sent as a body of the request, after the headers.

在 POST 请求中,参数作为请求的正文在标头之后发送。

To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.

要使用 HttpURLConnection 进行 POST,您需要在打开连接后将参数写入连接。

This code should get you started:

此代码应该可以帮助您入门:

String urlParameters  = "param1=a&param2=b&param3=c";
byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
int    postDataLength = postData.length;
String request        = "http://example.com/index.php";
URL    url            = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
   wr.write( postData );
}

回答by Martijn Verburg

I see some other answers have given the alternative, I personally think that intuitively you're doing the right thing ;). Sorry, at devoxx where several speakers have been ranting about this sort of thing.

我看到其他一些答案给出了替代方案,我个人认为直觉上你在做正确的事情;)。抱歉,在 devoxx 上,有几位演讲者一直在抱怨这种事情。

That's why I personally use Apache's HTTPClient/HttpCorelibraries to do this sort of work, I find their API to be easier to use than Java's native HTTP support. YMMV of course!

这就是我个人使用 Apache 的 HTTPClient/ HttpCore库来做这类工作的原因,我发现它们的 API 比 Java 的原生 HTTP 支持更容易使用。当然是YMMV!

回答by Craigo

I couldn't get Alan's exampleto actually do the post, so I ended up with this:

我无法让Alan 的例子真正做这个帖子,所以我最终得到了这个:

String urlParameters = "param1=a&param2=b&param3=c";
URL url = new URL("http://example.com/index.php");
URLConnection conn = url.openConnection();

conn.setDoOutput(true);

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

writer.write(urlParameters);
writer.flush();

String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((line = reader.readLine()) != null) {
    System.out.println(line);
}
writer.close();
reader.close();         

回答by hgoebl

I find HttpURLConnectionreally cumbersome to use. And you have to write a lot of boilerplate, error prone code. I needed a lightweight wrapper for my Android projects and came out with a library which you can use as well: DavidWebb.

我觉得用起来HttpURLConnection真的很麻烦。而且您必须编写大量样板文件、容易出错的代码。我的 Android 项目需要一个轻量级包装器,并推出了一个您也可以使用的库:DavidWebb

The above example could be written like this:

上面的例子可以这样写:

Webb webb = Webb.create();
webb.post("http://example.com/index.php")
        .param("param1", "a")
        .param("param2", "b")
        .param("param3", "c")
        .ensureSuccess()
        .asVoid();

You can find a list of alternative libraries on the link provided.

您可以在提供的链接上找到替代库的列表。

回答by Boann

Here is a simple example that submits a form then dumps the result page to System.out. Change the URL and the POST params as appropriate, of course:

这是一个简单的示例,它提交表单然后将结果页面转储到System.out. 当然,根据需要更改 URL 和 POST 参数:

import java.io.*;
import java.net.*;
import java.util.*;

class Test {
    public static void main(String[] args) throws Exception {
        URL url = new URL("http://example.net/new-message.php");
        Map<String,Object> params = new LinkedHashMap<>();
        params.put("name", "Freddie the Fish");
        params.put("email", "[email protected]");
        params.put("reply_to_thread", 10394);
        params.put("message", "Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He's so shellfish.");

        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String,Object> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c; (c = in.read()) >= 0;)
            System.out.print((char)c);
    }
}


If you want the result as a Stringinstead of directly printed out do:

如果您希望将结果作为String而不是直接打印出来,请执行以下操作:

        StringBuilder sb = new StringBuilder();
        for (int c; (c = in.read()) >= 0;)
            sb.append((char)c);
        String response = sb.toString();

回答by Manish Mistry

import java.net.*;

public class Demo{

  public static void main(){

       String data = "data=Hello+World!";
       URL url = new URL("http://localhost:8084/WebListenerServer/webListener");
       HttpURLConnection con = (HttpURLConnection) url.openConnection();
       con.setRequestMethod("POST");
       con.setDoOutput(true);
       con.getOutputStream().write(data.getBytes("UTF-8"));
       con.getInputStream();

    }

}

回答by SergeyUr

I had the same issue. I wanted to send data via POST. I used the following code:

我遇到过同样的问题。我想通过POST发送数据。我使用了以下代码:

    URL url = new URL("http://example.com/getval.php");
    Map<String,Object> params = new LinkedHashMap<>();
    params.put("param1", param1);
    params.put("param2", param2);

    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    String urlParameters = postData.toString();
    URLConnection conn = url.openConnection();

    conn.setDoOutput(true);

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write(urlParameters);
    writer.flush();

    String result = "";
    String line;
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    while ((line = reader.readLine()) != null) {
        result += line;
    }
    writer.close();
    reader.close()
    System.out.println(result);

I used Jsoup for parse:

我使用 Jsoup 进行解析:

    Document doc = Jsoup.parseBodyFragment(value);
    Iterator<Element> opts = doc.select("option").iterator();
    for (;opts.hasNext();) {
        Element item = opts.next();
        if (item.hasAttr("value")) {
            System.out.println(item.attr("value"));
        }
    }

回答by rogerdpack

Appears that you also have to callconnection.getOutputStream()"at least once" (as well as setDoOutput(true)) for it to treat it as a POST.

看来您还必须调用connection.getOutputStream()“至少一次”(以及setDoOutput(true))才能将其视为 POST。

So the minimum required code is:

所以最低要求的代码是:

    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    //connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful
    connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call...
    connection.connect();
    connection.getOutputStream().close(); 

You can even use "GET" style parameters in the urlString, surprisingly. Though that might confuse things.

令人惊讶的是,您甚至可以在 urlString 中使用“GET”样式参数。虽然这可能会混淆事情。

You can also use NameValuePairapparently.

您显然也可以使用NameValuePair

回答by Pablo Rodriguez Bertorello

Try this pattern:

试试这个模式:

public static PricesResponse getResponse(EventRequestRaw request) {

    // String urlParameters  = "param1=a&param2=b&param3=c";
    String urlParameters = Piping.serialize(request);

    HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);

    PricesResponse response = null;

    try {
        // POST
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(urlParameters);
        writer.flush();

        // RESPONSE
        BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
        String json = Buffering.getString(reader);
        response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);

        writer.close();
        reader.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    conn.disconnect();

    System.out.println("PricesClient: " + response.toString());

    return response;
}

public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters) {

    return RestClient.getConnection(endPoint, "POST", urlParameters);

}


public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters) {

    System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
    HttpURLConnection conn = null;

    try {
        URL url = new URL(endPoint);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "text/plain");

    } catch (IOException e) {
        e.printStackTrace();
    }

    return conn;
}

回答by Abhisek

here i sent jsonobject as parameter //jsonobject={"name":"lucifer","pass":"abc"}//serverUrl = "http://192.168.100.12/testing" //host=192.168.100.12

这里我发送 jsonobject 作为参数 //jsonobject={"name":"lucifer","pass":"abc"}//serverUrl = " http://192.168.100.12/testing" //host=192.168.100.12

  public static String getJson(String serverUrl,String host,String jsonobject){

    StringBuilder sb = new StringBuilder();

    String http = serverUrl;

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(http);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(50000);
        urlConnection.setReadTimeout(50000);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Host", host);
        urlConnection.connect();
        //You Can also Create JSONObject here 
        OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
        out.write(jsonobject);// here i sent the parameter
        out.close();
        int HttpResult = urlConnection.getResponseCode();
        if (HttpResult == HttpURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream(), "utf-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            Log.e("new Test", "" + sb.toString());
            return sb.toString();
        } else {
            Log.e(" ", "" + urlConnection.getResponseMessage());
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
    }
    return null;
}