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

348

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

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();
}
现在我可能需要通过POST方法发送参数(即param1、param2、param3),因为它们很长。我想添加一个额外的参数到该方法中(即String httpMethod)。
为了能够通过GETPOST发送参数,我应该如何尽可能地修改上面的代码?
我希望通过更改
connection.setRequestMethod("GET");
connection.setRequestMethod("POST");

使用 HttpPost 也许可以解决问题,但是参数仍然通过 GET 方法发送。

HttpURLConnection 是否有任何有用的方法可以帮助解决问题? 是否有任何有用的 Java 工具?

非常感谢任何帮助。


Post参数是发送到HTTP头部而不是URL中的。 (您的POST URL将为http://example.com/index.php - dacwe
2
Java 1.6中未定义setRequestMethod方法:http://docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html - ante.sabo
2
将其转换为Http(s)UrlConnection... - Peter Kriens
扩展问题!有人知道如何将附件作为帖子参数发送吗? - therealprashant
18个回答

3
这个答案涵盖了使用自定义Java POJO进行POST调用的特定情况。
使用Maven依赖项Gson将我们的Java对象序列化为JSON。
使用以下依赖项安装Gson。
<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.5</version>
  <scope>compile</scope>
</dependency>

对于使用gradle的人可以使用以下内容。
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}

其他使用的导入:

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.*;
import org.apache.http.impl.client.CloseableHttpClient;
import com.google.gson.Gson;

现在,我们可以使用Apache提供的HttpPost。
private CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://example.com");

Product product = new Product(); //custom java object to be posted as Request Body
    Gson gson = new Gson();
    String client = gson.toJson(product);

    httppost.setEntity(new StringEntity(client, ContentType.APPLICATION_JSON));
    httppost.setHeader("RANDOM-HEADER", "headervalue");
    //Execute and get the response.
    HttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (IOException e) {
        throw new InternalServerErrorException("Post fails");
    }
    Response.Status responseStatus = Response.Status.fromStatusCode(response.getStatusLine().getStatusCode());
    return Response.status(responseStatus).build();

上述代码将返回从 POST 调用接收到的响应代码。

2
我强烈推荐使用基于Apache HTTP API构建的http-request

对于您的情况,您可以查看以下示例:

private static final HttpRequest<String.class> HTTP_REQUEST = 
      HttpRequestBuilder.createPost("http://example.com/index.php", String.class)
           .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
           .build();

public void sendRequest(String request){
     String parameters = request.split("\\?")[1];
     ResponseHandler<String> responseHandler = 
            HTTP_REQUEST.executeWithQuery(parameters);

   System.out.println(responseHandler.getStatusCode());
   System.out.println(responseHandler.get()); //prints response body
}

如果您对响应主体不感兴趣

private static final HttpRequest<?> HTTP_REQUEST = 
     HttpRequestBuilder.createPost("http://example.com/index.php").build();

public void sendRequest(String request){
     ResponseHandler<String> responseHandler = 
           HTTP_REQUEST.executeWithQuery(parameters);
}

针对使用http-request发送POST请求的一般性操作:请阅读文档并参考以下答案:在JAVA中使用JSON字符串进行HTTP POST请求在Java中发送HTTP POST请求在Java中使用JSON进行HTTP POST请求


2

我在这里将jsonobject作为参数发送了 //jsonobject={"name":"lucifer","pass":"abc"}//服务器网址 = "http://192.168.100.12/testing" //主机=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;
}

2

你好,请使用这个类来改进你的POST方法。

public static JSONObject doPostRequest(HashMap<String, String> data, String url) {

    try {
        RequestBody requestBody;
        MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);

        if (data != null) {


            for (String key : data.keySet()) {
                String value = data.get(key);
                Utility.printLog("Key Values", key + "-----------------" + value);

                mBuilder.addFormDataPart(key, value);

            }
        } else {
            mBuilder.addFormDataPart("temp", "temp");
        }
        requestBody = mBuilder.build();


        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();
        Utility.printLog("URL", url);
        Utility.printLog("Response", responseBody);
        return new JSONObject(responseBody);

    } catch (UnknownHostException | UnsupportedEncodingException e) {

        JSONObject jsonObject=new JSONObject();

        try {
            jsonObject.put("status","false");
            jsonObject.put("message",e.getLocalizedMessage());
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        Log.e(TAG, "Error: " + e.getLocalizedMessage());
    } catch (Exception e) {
        e.printStackTrace();
        JSONObject jsonObject=new JSONObject();

        try {
            jsonObject.put("status","false");
            jsonObject.put("message",e.getLocalizedMessage());
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
    }
    return null;
}

0

现在我需要创建一个 HTTP 请求类,这可能不是最高效的类,但它可以工作。 我从这个页面收集了一些代码并使其更加动态。

任何需要完整代码的人,我在下面附上了它。 如果想知道如何使用它的示例,您可以查看main方法。

此外,如果您愿意在线改进这些类,非常欢迎您帮助我使这个类更好。

import java.net.*;
import java.util.*;
import java.nio.charset.*;
import java.io.*;
  
public class HttpRequest {
    
    
    String result = "";
    
    HttpRequest(String _url, String _method, Map<String, String> _postData, String _contentType) {
        
        try {
            URL url = new URL( _url );
            URLConnection con = url.openConnection();
            HttpURLConnection http = (HttpURLConnection)con;
            http.setRequestMethod(_method); // PUT is another valid option
            http.setDoOutput(true);         
            
            StringJoiner sj = new StringJoiner("&");
            for(Map.Entry<String,String> entry : _postData.entrySet())
                sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + entry.getValue());
                //sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue()));
            byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
            int length = out.length;
            http.setFixedLengthStreamingMode(length);
            http.setRequestProperty("Content-Type", _contentType);
            http.setRequestProperty( "charset", "utf-8");
            http.setRequestProperty( "Content-Length", Integer.toString( length ));
            http.setInstanceFollowRedirects( false );
            http.setUseCaches( false );
            http.connect();
            try(OutputStream os = http.getOutputStream()) {
                os.write(out);
            }
            if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
                try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(http.getInputStream()))) {
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                  result = result + line;
                }
            }
          } else {
            System.out.println("Bad response!");
          }
        }catch (IOException e) {
            // writing exception to log
            e.printStackTrace();
        }
        
    }
    
    
    HttpRequest(String _url, String _method, Map<String, String> _postData) {
        this(_url, _method, _postData, "text/html");
    }
    
    HttpRequest(String _url, String _method) {
        this(_url, _method, new HashMap<String, String>());
    }
    
    HttpRequest(String _url) {
        this(_url, "GET");
    }
    
    
    public String toString() {
        return result;
    }
    
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Map<String, String> postData = new HashMap<String, String>();
        postData.putIfAbsent("email", "test@test.com");
        postData.putIfAbsent("password", "test");
        
        HttpRequest result = new HttpRequest("https://httpbin.org/anything", "POST", postData, "application/x-www-form-urlencoded");
        System.out.println(result.toString());
    }
}


0

我采用了Boann的答案,并使用它创建了一个更灵活的查询字符串生成器,支持列表和数组,就像php的http_build_query方法一样:

public static byte[] httpBuildQueryString(Map<String, Object> postsData) throws UnsupportedEncodingException {
    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : postsData.entrySet()) {
        if (postData.length() != 0) postData.append('&');

        Object value = param.getValue();
        String key = param.getKey();

        if(value instanceof Object[] || value instanceof List<?>)
        {
            int size = value instanceof Object[] ? ((Object[])value).length : ((List<?>)value).size();
            for(int i = 0; i < size; i++)
            {
                Object val = value instanceof Object[] ? ((Object[])value)[i] : ((List<?>)value).get(i);
                if(i>0) postData.append('&');
                postData.append(URLEncoder.encode(key + "[" + i + "]", "UTF-8"));
                postData.append('=');            
                postData.append(URLEncoder.encode(String.valueOf(val), "UTF-8"));
            }
        }
        else
        {
            postData.append(URLEncoder.encode(key, "UTF-8"));
            postData.append('=');            
            postData.append(URLEncoder.encode(String.valueOf(value), "UTF-8"));
        }
    }
    return postData.toString().getBytes("UTF-8");
}

0

对于那些在使用 $_POST 接收请求时遇到麻烦的人,因为您期望键值对:

虽然所有答案都非常有帮助,但我缺乏一些基本的理解,即要发布哪个字符串,因为在旧版 apache HttpClient 中我使用了

new UrlEncodedFormEntity(nameValuePairs); (Java)

然后可以在php中使用$_POST获取键值对。

据我现在的理解,需要手动构建该字符串才能进行发布。因此,该字符串需要如下所示:

val data = "key1=val1&key2=val2"

但是相反地,将它添加到URL中并不是把它发布在头部。

另一个选择是使用JSON字符串:

val data = "{\"key1\":\"val1\",\"key2\":\"val2\"}" // {"key1":"val1","key2":"val2"}

使用 PHP 无需 $_POST 获取它:

$json_params = file_get_contents('php://input');
// echo_p("Data: $json_params");
$data = json_decode($json_params, true);

在这里,您可以找到Kotlin的示例代码:

class TaskDownloadTest : AsyncTask<Void, Void, Void>() {
    override fun doInBackground(vararg params: Void): Void? {
        var urlConnection: HttpURLConnection? = null

        try {

            val postData = JsonObject()
            postData.addProperty("key1", "val1")
            postData.addProperty("key2", "val2")

            // reformat json to key1=value1&key2=value2
            // keeping json because I may change the php part to interpret json requests, could be a HashMap instead
            val keys = postData.keySet()
            var request = ""
            keys.forEach { key ->
                // Log.i("data", key)
                request += "$key=${postData.get(key)}&"
            }
            request = request.replace("\"", "").removeSuffix("&")
            val requestLength = request.toByteArray().size
            // Warning in Android 9 you need to add a line in the application part of the manifest: android:usesCleartextTraffic="true"
            // https://dev59.com/w1cO5IYBdhLWcg3wWgU0
            val url = URL("http://10.0.2.2/getdata.php")
            urlConnection = url.openConnection() as HttpURLConnection
            // urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") // apparently default
            // Not sure what these are for, I do not use them
            // urlConnection.setRequestProperty("Content-Type", "application/json")
            // urlConnection.setRequestProperty("Key","Value")
            urlConnection.readTimeout = 5000
            urlConnection.connectTimeout = 5000
            urlConnection.requestMethod = "POST"
            urlConnection.doOutput = true
            // urlConnection.doInput = true
            urlConnection.useCaches = false
            urlConnection.setFixedLengthStreamingMode(requestLength)
            // urlConnection.setChunkedStreamingMode(0) // if you do not want to handle request length which is fine for small requests

            val out = urlConnection.outputStream
            val writer = BufferedWriter(
                OutputStreamWriter(
                    out, "UTF-8"
                )
            )
            writer.write(request)
            // writer.write("{\"key1\":\"val1\",\"key2\":\"val2\"}") // {"key1":"val1","key2":"val2"} JsonFormat or just postData.toString() for $json_params=file_get_contents('php://input'); json_decode($json_params, true); in php
            // writer.write("key1=val1&key2=val2") // key=value format for $_POST in php
            writer.flush()
            writer.close()
            out.close()

            val code = urlConnection.responseCode
            if (code != 200) {
                throw IOException("Invalid response from server: $code")
            }

            val rd = BufferedReader(
                InputStreamReader(
                    urlConnection.inputStream
                )
            )
            var line = rd.readLine()
            while (line != null) {
                Log.i("data", line)
                line = rd.readLine()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            urlConnection?.disconnect()
        }

        return null
    }
}

-1

看起来您还必须至少调用connection.getOutputStream()(以及setDoOutput(true))才能将其视为POST请求。

因此,最少所需的代码是:

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

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

显然,您还可以使用NameValuePair


POST参数在哪里? - Yousha Aleayoub
为什么人们要踩这个帖子?虽然没有参数(即没有有效载荷),但这是关于如何进行POST请求的笔记... - rogerdpack

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接