dongshendie8849
2014-10-01 06: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?

图片转代码服务由CSDN问答提供 功能建议

我使用php完成了卷曲操作。 这是我的代码。

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

现在 我需要在java中重写这段代码。 我对Java中的HttpURLConnection不太熟悉。 任何人都可以帮忙吗?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongtui4038 2014-10-01 07: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 :)

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题