java

时间:2016-03-04 09:13:12

标签: java post curl

这是我的curl命令:

curl https://login.xyz.com/v1/oauth/token -H "Accept:
application/json" --data 'client_id=client_id' --data
'client_secret=client_secret' --data 'redirect_uri=redirect_uri'
--data 'code=code'

我正试图在java中发布它。这就是我想要做的事情:

String resourceUrl = "https://login.xyz.com/v1/oauth/token?client_id=<client.id>&client_secret=<client.secret>&redirect_uri=https://login.xyz.com/user/login&code=<code>";
HttpURLConnection httpcon = (HttpURLConnection) ((new URL(resourceUrl).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();      
System.out.println(httpcon.getHeaderField(0));

但我收到HTTP / 1.1 500内部服务器错误

2 个答案:

答案 0 :(得分:1)

我没有测试,只是通过查看文档和源代码,我可以看到你的curl命令和Java实现之间的一些区别:

卷曲:

  • 执行POST
  • Content-Type为application / x-www-form-urlencoded

Curl manpage

  

-d, - data

     

(HTTP)将POST请求中的指定数据发送到HTTP服务器,   与用户填写HTML时浏览器的操作方式相同   表单并按下提交按钮。这将导致卷曲通过   使用content-type将数据发送到服务器   应用程序/ x-WWW窗体-urlencoded。比较-F, - form。

另请参阅:How are parameters sent in an HTTP POST request?

Java实现:

  • 执行POST但是URL是GET相似的(您将请求方法设置为POST但是您在URL查询字符串中传递参数)
  • Content-Type是application / json

我希望这会有所帮助。

答案 1 :(得分:1)

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException; 
import java.net.HttpURLConnection;
import java.net.URL;

public class CURLTest {
public void main(String[] args) throws IOException {
    sendData();
}

public String sendData() throws IOException {
// curl_init and url


URL url = new URL( "Put the Request here");
HttpURLConnection con = (HttpURLConnection) url.openConnection();

// CURLOPT_POST
con.setRequestMethod("POST");

// CURLOPT_FOLLOWLOCATION
con.setInstanceFollowRedirects(true);

String postData = "my_data_for_posting";
con.setRequestProperty("Content-length",
        String.valueOf(postData.length()));

con.setDoOutput(true);
con.setDoInput(true);

DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(postData);
output.close();

// "Post data send ... waiting for reply");
int code = con.getResponseCode(); // 200 = HTTP_OK
System.out.println("Response    (Code):" + code);
System.out.println("Response (Message):" + con.getResponseMessage());

// read the response
DataInputStream input = new DataInputStream(con.getInputStream());
int c;
StringBuilder resultBuf = new StringBuilder();
while ((c = input.read()) != -1) {
    resultBuf.append((char) c);
}
input.close();

return resultBuf.toString();
}
}

这是我将如何做的一个例子