在java中相当于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内部服务器错误
我没有测试,只是通过查看文档和源代码,我可以看到curl命令和Java实现之间的一些区别:
卷曲:
卷曲手册页:
-d, - 数据
(HTTP)将POST请求中的指定数据发送到HTTP服务器,方式与浏览器在用户填写HTML表单并按下提交按钮时执行的操作相同。 这将导致curl使用内容类型application / x-www-form-urlencoded将数据传递到服务器。 与-F,--form比较。
另请参阅:如何在HTTP POST请求中发送参数?
Java实现:
我希望这有帮助。
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();
}
}
这是一个例子,我将如何做到这一点
链接地址: http://www.djcxy.com/p/41331.html