Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用params和Body创建一个HttpPost_Java_Post - Fatal编程技术网

Java 使用params和Body创建一个HttpPost

Java 使用params和Body创建一个HttpPost,java,post,Java,Post,我需要用Java复制一篇邮递员文章。 通常,我必须在URL中仅使用参数创建一个HttpPost,因此很容易构建: ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("username", username)); post.setEntity(new UrlEncodedFormEntity(p

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

ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
post.setEntity(new UrlEncodedFormEntity(postParameters, Consts.UTF_8));
ArrayList后参数=新的ArrayList();
添加(新的BasicNameValuePair(“用户名”,用户名));
setEntity(新的UrlEncodedFormEntity(后参数,常量UTF_8));
但是如果我有一篇像下图这样的帖子,URL和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
}
HttpClient-client=HttpClientBuilder.create().build();
HttpPost=newhttppost(“someUrls.com/upload”);
ArrayList后参数=新的ArrayList();
添加(新的BasicNameValuePair(“用户名”,用户名));
添加(新的BasicNameValuePair(“密码”,password));
添加(新的BasicNameValuePair(“所有者”,所有者));
添加(新的BasicNameValuePair(“目的地”,目的地));
试一试{
setEntity(新的UrlEncodedFormEntity(后参数,常量UTF_8));
HttpResponse HttpResponse=client.execute(post);
//做点什么
}捕获(例外e){
//做点什么
}
但是我如何将“filename”和“filedata”参数与URL中的参数放在一起呢? 实际上我使用的是org .Apache库,但我也可以考虑其他库。
感谢所有愿意帮忙的人

您可以使用下面的代码在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());
   }
}
我认为这个问题和这个问题都是关于相似的问题,并且都有很好的答案


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

我决定这样做:

  • 放置POST URL头参数
  • 将文件名和文件数据添加为多个部件
  • 这里是代码

    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;
    }
    

    你能分享更多的代码吗?比如你是如何制作请求的,什么类型的对象是代码<邮政> <代码>等等。你也应该考虑,如果你可以,使用一个库来处理这些请求,例如:代码> OKHTTP @ GuyGrin OK,我增加了一个例子。谢谢你的关注。