dongshendie8849 2014-09-30 22:51
浏览 23
已采纳

使用java进行卷曲操作[关闭]

I have done a curl operation using php. This is my code.

$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode($username . ":" . $password)));
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonObjectFields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
curl_close($ch);

Now I need to rewrite this code in java. I am not much familler with HttpURLConnection in java. Can any body help?

  • 写回答

1条回答 默认 最新

  • dongtui4038 2014-09-30 23:02
    关注

    Yes you can use HttpURLConnection

    HttpURLConnection myConnection = (HttpURLConnection) ((new URL("myurl").openConnection()));
    myConnection.setDoOutput(true);
    myConnection.setRequestProperty("Content-Type", "application/json");
    myConnection.setRequestProperty("Accept", "application/json");
    myConnection.setRequestMethod("POST");
    myConnection.connect();
    
    String jsonData = "{'foo' : 'bar'}";
    byte[] outputBytes = jsonData.getBytes("UTF-8");
    OutputStream os = myConnection.getOutputStream();
    os.write(outputBytes);
    os.close();
    

    I hope my answer is clear enough. If you have any question regarding my answer you can ask in the comment :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部