java 类似curl,什么将相当于在java中跟随curl命令

i need to convert the following curl command into java command.

$curl_handle = curl_init ();

curl_setopt ($curl_handle, CURLOPT_URL,$url);`enter code here`

curl_setopt ($curl_handle, CURLOPT_FOLLOWLOCATION, 1);

curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1);

curl_setopt ($curl_handle, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt ($curl_handle, CURLOPT_POST, 1);

curl_setopt ($curl_handle, CURLOPT_POSTFIELDS, $postfields);

//echo $postfields;

$curl_result = curl_exec ($curl_handle) or die ("There has been a CURL_EXEC error");

解决方案

Http(s)UrlConnection may be your weapon of choice:

public String sendData() throws IOException {

// curl_init and url

URL url = new URL("http://some.host.com/somewhere/to/");

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();

}

I'm not quite sure about the HTTPS_VERIFYPEER-thing, but this may give you a starting point.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值