curl command equivalent in java
Here is my curl command:
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'
I'm trying to post that in java. Here is what i was trying to do:
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));
But I'm getting HTTP/1.1 500 Internal Server Error
I didn't test but just by looking at the documentation and your source code, I can see some differences between your curl command and the Java implementation:
Curl:
Curl manpage:
-d, --data
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -F, --form.
See also: How are parameters sent in an HTTP POST request?
Java implementation:
I hope this helps.
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/41332.html下一篇: 在java中相当于curl命令