【问题标题】:Sending POST request with Form params through java don´t get response通过java发送带有表单参数的POST请求没有得到响应
【发布时间】:2015-07-15 18:33:08
【问题描述】:

我正在尝试通过 Java 向 REST Web 服务发送请求。

我需要向 Web 服务发送一些表单参数,因为它们太大而无法通过 queryParams 发送。

发送的httpRequest方法如下:

public static String sendPostWithParams(String urlParam, Map<String, Object> params) throws Exception {
    URL url = new URL(urlParam);

    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);
    conn.connect(); 

    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

    wr.flush();
    wr.close();

    int responseCode = conn.getResponseCode();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    // print result
    return response.toString();
}

我尝试通过 Postman 发送请求,它工作正常,就像预期的那样。但是当我尝试通过 Java 发送请求时,我在控制台中打印了以下两行,然后它就冻结在那里直到超时。

15:18:18,160 INFORMACIÓN [org.jboss.resteasy.cdi.CdiInjectorFactory] (http--0.0.0.0-8080-1) Found BeanManager at java:comp/BeanManager
15:18:18,170 INFORMACIÓN [org.jboss.resteasy.spi.ResteasyDeployment] (http--0.0.0.0-8080-1) Deploying javax.ws.rs.core.Application: class .com.services.rest.ApplicationConfig$Proxy$_$$_WeldClientProxy

没有调用 Web 服务,因为我在那里有一个断点,但它永远不会到达它。

所以我认为问题可能出在我通过 Java 生成请求的方式上,但我还没有找到另一种方法。

提前致谢。

【问题讨论】:

    标签: java rest httprequest


    【解决方案1】:

    使用HttpClient

                HttpClient client = new DefaultHttpClient();
    
                HttpPost request = new HttpPost("your url");                
    
                //Set Headers
                request.setHeader("Accept", "application/json");
                request.setHeader("Content-Type", "application/x-www-form-urlencoded");
                //Add Parameters
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("login", "kainix"));
                params.add(new BasicNameValuePair("pass", "google@123"));
                request.setEntity(new UrlEncodedFormEntity(params));
    
    
                //Sends Request                
                HttpResponse response = client.execute(request);  
    
                //Read From Response
                StringBuilder result = new StringBuilder();
                BufferedReader reader;
                InputStream inputStream = response.getEntity().getContent();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String inputLine;
                while ((inputLine = reader.readLine()) != null) {
                    result.append(inputLine);
                }
    
                System.out.println(result);
    

    试试这个简单明了,你需要httpclient-4.xhttpcore-4.x这个jar文件

    【讨论】:

    • 谢谢,我会试试的,但是没有办法用已经包含的 java.net 来做吗?因为我已经在使用它来发送带有查询参数的 POST 并且它工作正常。谢谢
    • 我正在尝试,当您执行“HttpClient client = new HttpClient();”时,在第一行中我收到一条错误消息,提示无法使用 HttpClient。
    • 我的错 HttpClient client=new DefaultHttpClient()
    • 但如果你已经下载了HttpClient-4.5 jar,那么你可能想要使用ClosableHttpClient client=HttpClients.createDefault();,因为DefaultHttpClient已被弃用
    • @javapai 上面的东西你试过了吗
    【解决方案2】:

    好的,我已经解决了。我发送请求的方式没问题,服务也没问题,但是我使用 Eclipse Luna 在调试模式下运行 JBoss,这让它挂在那里。所以我在运行模式下运行它,它运行良好。因此,如果其他人面对它,请在运行模式下运行并尝试。 感谢您的帮助。

    【讨论】:

    • 是的,感谢您的回答,使用表单参数发送帖子请求的两种方式都可以正常工作
    猜你喜欢
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 2013-01-23
    相关资源
    最近更新 更多