简体   繁体   English

如何建立HTTP POST URL连接?

[英]How to make an HTTP POST URL connection?

I am accessing a web service by an HTTP POST method as below: 我正在通过HTTP POST方法访问Web服务,如下所示:

But the response contains nothing. 但是响应中没有任何内容。 I was expecting a JSON string here. 我在这里期待一个JSON字符串。 Are JSON read in a different way? JSON是否以其他方式读取?

You can keep the type as HttpURLConnection instead of URLConnection. 您可以将类型保留为HttpURLConnection而不是URLConnection。 It allows to specify HTTP method. 它允许指定HTTP方法。

HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");

I agree that using a HttpUtlConnection or HTTPClient is going to make you life easier, but have a look at setDoOutput 我同意使用HttpUtlConnection或HTTPClient将使您的生活更轻松,但是请看一下setDoOutput

http://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#setDoOutput(boolean) http://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#setDoOutput(boolean)

and

What exactly does URLConnection.setDoOutput() affect? URLConnection.setDoOutput()到底会影响什么?

The problem is here 问题在这里

URLConnection connection = (HttpURLConnection)url.openConnection();

make connection an instance of HttpURLConnection 使connection成为HttpURLConnection的实例

Adding to Shammiz answer 添加到Shammiz答案

Without cast Make use of URLConnection.html#setDoOutput(boolean) 没有强制转换时使用URLConnection.html#setDoOutput(boolean)

A URL connection can be used for input and/or output. URL连接可用于输入和/或输出。 Set the DoOutput flag to true if you intend to use the URL connection for output, false if not. 如果您打算将URL连接用于输出,请将DoOutput标志设置为true,否则将其设置为false。 The default is false. 默认为false。

Passing true , triggers post . 传递true会触发post

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM