有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用params和Body生成HttpPost

我需要用Java复制一篇邮递员文章。 通常,我必须在URL中仅使用参数创建一个HttpPost,因此很容易构建:

ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
post.setEntity(new UrlEncodedFormEntity(postParameters, Consts.UTF_8));

但是如果我有一篇像下图这样的帖子,URL和Body中都有参数,我该怎么办呢?? POST call with Params and Body 现在我正在制作HttpPost,如下所示:

HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("someUrls.com/upload");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
postParameters.add(new BasicNameValuePair("password", password));
postParameters.add(new BasicNameValuePair("owner", owner));
postParameters.add(new BasicNameValuePair("destination", destination));
try{
    post.setEntity(new UrlEncodedFormEntity(postParameters, Consts.UTF_8));
    HttpResponse httpResponse = client.execute(post);
    //Do something
}catch (Exception e){
    //Do something
}

但是我如何将“filename”和“filedata”参数与URL中的参数放在一起呢? 实际上我在用org。Apache库,但我也可以考虑其他库。

感谢所有愿意帮忙的人


共 (3) 个答案

  1. # 1 楼答案

    我决定这样做:

    1. 放置POST URL头参数
    2. 将文件名和文件数据添加为多个部件

    这里是代码

    private boolean uploadQueue(String username, String password, String filename, byte[] fileData)
    {
        HttpClient client = HttpClientBuilder.create().build();
        String URL = "http://post.here.com:8080/";
        HttpPost post = new HttpPost(URL +"?username="+username+"&password="password);
    
        try
        {
            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            entityBuilder.addBinaryBody("filedata", fileData, ContentType.DEFAULT_BINARY, filename);
            entityBuilder.addTextBody("filename", filename);
    
            post.setEntity(entityBuilder.build());
    
            HttpResponse httpResponse = client.execute(post);
    
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                logger.info(EntityUtils.toString(httpResponse.getEntity()));
    
                return true;
            } 
            else
            {
                logger.info(EntityUtils.toString(httpResponse.getEntity()));
    
                return false;
            }
        }
        catch (Exception e)
        {
            logger.error("Error during Updload Queue phase:"+e.getMessage());
        }
    
        return false;
    }
    
  2. # 2 楼答案

    我认为this问题和this问题都是关于类似的问题,并且都有很好的答案

    我建议您使用this库,因为它维护良好,如果您愿意,使用起来也很简单

  3. # 3 楼答案

    您可以使用下面的代码在POST方法调用中以“application/x-www-form-urlencoded”的形式传递主体参数

    package han.code.development;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.URL;
    
    import javax.net.ssl.HttpsURLConnection;
    
    public class HttpPost
    {
        public String getDatafromPost()
        {
            BufferedReader br=null;
            String outputData;
            try
            {
                String urlString="https://www.google.com"; //you can replace that with your URL
                URL url=new URL(urlString);
                HttpsURLConnection connection=(HttpsURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.addRequestProperty("Authorization", "Replace with your token"); // if you have any accessToken to authorization, just replace
                connection.setDoOutput(true);
                String data="filename=file1&filedata=asdf1234qwer6789";
    
                PrintWriter out;
                if((data!=null)) 
                {
                     out = new PrintWriter(connection.getOutputStream());
                     out.println(data);
                     out.close();
                }
                System.out.println(connection.getResponseCode()+" "+connection.getResponseMessage());
                br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder sb=new StringBuilder();
                String str=br.readLine();
                while(str!=null)
                {
                    sb.append(str);
                    str=br.readLine();
                }
    
                outputData=sb.toString();
                return outputData;
           }
           catch(Exception e)
           {
               e.printStackTrace();
           }
           return null;
       }
       public static void main(String[] args)
       {
           HttpPost post=new HttpPost();
           System.out.println(post.getDatafromPost());
       }
    }