Java - sending HTTP parameters via POST method easily

前端 未结 17 1734
借酒劲吻你
借酒劲吻你 2020-11-21 05:54

I am successfully using this code to send HTTP requests with some parameters via GET method

void sendRequest(String request)
{
            


        
17条回答
  •  滥情空心
    2020-11-21 06:33

    I took Boann's answer and used it to create a more flexible query string builder that supports lists and arrays, just like php's http_build_query method:

    public static byte[] httpBuildQueryString(Map postsData) throws UnsupportedEncodingException {
        StringBuilder postData = new StringBuilder();
        for (Map.Entry 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");
    }
    

提交回复
热议问题