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

dan*_*dan 310 java post http httpurlconnection

我成功地使用此代码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();
}
Run Code Online (Sandbox Code Playgroud)

现在我可能需要通过POST方法发送参数(即param1,param2,param3),因为它们非常长.我想在该方法中添加一个额外的参数(即String httpMethod).

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

我希望改变

connection.setRequestMethod("GET");
Run Code Online (Sandbox Code Playgroud)

connection.setRequestMethod("POST");
Run Code Online (Sandbox Code Playgroud)

本来可以做到的,但参数仍然是通过GET方法发送的.

HttpURLConnection任何方法可以帮助吗?有没有有用的Java构造?

任何帮助将非常感谢.

Ala*_*nse 462

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

在POST请求中,参数在标头之后作为请求的主体发送.

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

这段代码应该让你入门:

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 );
}
Run Code Online (Sandbox Code Playgroud)

  • @Alan Geleynse:'url.openconnection()'无法打开连接.如果您没有指定connect()语句,则在您写入http请求正文/听到并发送它时会打开连接.我用证书试过这个.只有在调用connect或向服务器发送数据后才会进行ssl握手. (40认同)
  • getBytes()使用环境的默认charaset,而不是UTF-8 charset = utf-8必须遵循以下内容类型:application/x-www-form-urlencoded; charset = utf-8在示例中进行两次字节转换.应该这样做:byte [] data = urlParameters.getData("UTF-8"); .connection.getOutputStream()写(数据); 没有用关闭和冲洗和断开连接 (13认同)
  • @PeterKriens感谢您的加入 - 我相信您的意思是`byte [] data = urlParameters.getBytes(Charset.forName("UTF-8"))`:). (8认同)
  • @AlanGeleynse你不想念wr.flush(); 和wr.close(); 在末尾? (7认同)
  • 如果没有工作,怎么会有这么多的赞成?你需要调用`conn.getResponseCode()`或`conn.getInputStream()`否则它不会发送任何数据. (7认同)
  • 嗨,艾伦.在您的代码中没有调用connect().是对的吗? (2认同)

Boa*_*ann 225

这是一个提交表单然后将结果页面转储到的简单示例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", "fishie@seamail.example.com");
        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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想把结果作为一个String而不是直接打印出来做:

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

  • +1是唯一关心参数编码的人. (42认同)
  • +1表示使用Map的通用例程. (15认同)
  • 不幸的是,这段代码假设内容的编码是"UTF-8",但情况并非总是如此.要检索字符集,应该获取标题"Content-Type"并解析其中的字符集.当该标头不可用时,请使用标准的http:`ISO-8859-1`. (3认同)

Cra*_*igo 62

我无法得到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();         
Run Code Online (Sandbox Code Playgroud)


hgo*_*ebl 23

我发现HttpURLConnection使用起来非常麻烦.而且你必须编写很多样板,容易出错的代码.我的Android项目需要一个轻量级的包装器,并且还提供了一个可以使用的库:DavidWebb.

上面的例子可以这样写:

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

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

  • 我会upvote.我已经成功地在我的一个应用程序中使用了DavidWebb,并且我将很快再开发两个.非常好用. (3认同)
  • 我不会投票,因为你的帖子不是一个答案而是一个广告......但是,我玩过你的图书馆,我喜欢它。非常简洁;大量的语法糖;如果您像我一样使用 Java 作为一种脚本语言,那么它是一个很棒的库,可以非常快速有效地添加一些 http 交互。零样板有时很有价值,它可能对 OP 有用。 (2认同)

Mar*_*urg 10

我看到其他一些答案已经给出了替代方案,我个人认为直觉上你做的是正确的事情;).对不起,在devoxx,有几位发言者一直在咆哮这种事情.

这就是为什么我个人使用Apache的HTTPClient/HttpCore库来完成这类工作,我发现他们的API比Java的本机HTTP支持更容易使用.YMMV当然!


Pan*_*tel 10

我已阅读上述答案并创建了一个实用程序类来简化HTTP请求.我希望它会对你有所帮助.

方法调用

  // send params with Hash Map
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("email","me@example.com");
    params.put("password","12345");

    //server url
    String url = "http://www.example.com";

    // static class "HttpUtility" with static method "newRequest(url,method,callback)"
    HttpUtility.newRequest(url,HttpUtility.METHOD_POST,params, new HttpUtility.Callback() {
        @Override
        public void OnSuccess(String response) {
        // on success
           System.out.println("Server OnSuccess response="+response);
        }
        @Override
        public void OnError(int status_code, String message) {
        // on error
              System.out.println("Server OnError status_code="+status_code+" message="+message);
        }
    });
Run Code Online (Sandbox Code Playgroud)

实用类

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
import static java.net.HttpURLConnection.HTTP_OK;

public class HttpUtility {

 public static final int METHOD_GET = 0; // METHOD GET
 public static final int METHOD_POST = 1; // METHOD POST

 // Callback interface
 public interface Callback {
  // abstract methods
  public void OnSuccess(String response);
  public void OnError(int status_code, String message);
 }
 // static method
 public static void newRequest(String web_url, int method, HashMap < String, String > params, Callback callback) {

  // thread for handling async task
  new Thread(new Runnable() {
   @Override
   public void run() {
    try {
     String url = web_url;
     // write GET params,append with url
     if (method == METHOD_GET && params != null) {
      for (Map.Entry < String, String > item: params.entrySet()) {
       String key = URLEncoder.encode(item.getKey(), "UTF-8");
       String value = URLEncoder.encode(item.getValue(), "UTF-8");
       if (!url.contains("?")) {
        url += "?" + key + "=" + value;
       } else {
        url += "&" + key + "=" + value;
       }
      }
     }

     HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
     urlConnection.setUseCaches(false);
     urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // handle url encoded form data
     urlConnection.setRequestProperty("charset", "utf-8");
     if (method == METHOD_GET) {
      urlConnection.setRequestMethod("GET");
     } else if (method == METHOD_POST) {
      urlConnection.setDoOutput(true); // write POST params
      urlConnection.setRequestMethod("POST");
     }

     //write POST data 
     if (method == METHOD_POST && params != null) {
      StringBuilder postData = new StringBuilder();
      for (Map.Entry < String, String > item: params.entrySet()) {
       if (postData.length() != 0) postData.append('&');
       postData.append(URLEncoder.encode(item.getKey(), "UTF-8"));
       postData.append('=');
       postData.append(URLEncoder.encode(String.valueOf(item.getValue()), "UTF-8"));
      }
      byte[] postDataBytes = postData.toString().getBytes("UTF-8");
      urlConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
      urlConnection.getOutputStream().write(postDataBytes);

     }
     // server response code
     int responseCode = urlConnection.getResponseCode();
     if (responseCode == HTTP_OK && callback != null) {
      BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
      StringBuilder response = new StringBuilder();
      String line;
      while ((line = reader.readLine()) != null) {
       response.append(line);
      }
      // callback success
      callback.OnSuccess(response.toString());
      reader.close(); // close BufferReader
     } else if (callback != null) {
      // callback error
      callback.OnError(responseCode, urlConnection.getResponseMessage());
     }

     urlConnection.disconnect(); // disconnect connection
    } catch (IOException e) {
     e.printStackTrace();
     if (callback != null) {
      // callback error
      callback.OnError(500, e.getLocalizedMessage());
     }
    }
   }
  }).start(); // start thread
 }
}
Run Code Online (Sandbox Code Playgroud)


小智 9

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();

    }

}
Run Code Online (Sandbox Code Playgroud)

  • WTH`import java.net.*;`! (4认同)

Chi*_*tel 6

GET 和 POST 方法设置如下... api 调用的两种类型 1) get() 和 2) post() 。get() 方法从 api json 数组获取值以获取值,而 post() 方法在我们的数据发布中使用 url 并获取响应。

 public class HttpClientForExample {

    private final String USER_AGENT = "Mozilla/5.0";

    public static void main(String[] args) throws Exception {

        HttpClientExample http = new HttpClientExample();

        System.out.println("Testing 1 - Send Http GET request");
        http.sendGet();

        System.out.println("\nTesting 2 - Send Http POST request");
        http.sendPost();

    }

    // HTTP GET request
    private void sendGet() throws Exception {

        String url = "http://www.google.com/search?q=developer";

        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);

        // add request header
        request.addHeader("User-Agent", USER_AGENT);

        HttpResponse response = client.execute(request);

        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + 
                       response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                       new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());

    }

    // HTTP POST request
    private void sendPost() throws Exception {

        String url = "https://selfsolve.apple.com/wcResults.do";

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        // add header
        post.setHeader("User-Agent", USER_AGENT);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
        urlParameters.add(new BasicNameValuePair("cn", ""));
        urlParameters.add(new BasicNameValuePair("locale", ""));
        urlParameters.add(new BasicNameValuePair("caller", ""));
        urlParameters.add(new BasicNameValuePair("num", "12345"));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = client.execute(post);
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " + 
                                    response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());

    }

}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

781352 次

最近记录:

5 年,11 月 前