卷曲到java转换

时间:2014-09-30 14:13:55

标签: java php curl

我正在尝试将我在php中创建的POST请求转换为Java。该请求基于curl。我可以使用GET方法发出请求但是当我尝试切换到POST方法时它不起作用...

这是php请求,所有身份验证变量和数据都在之前初始化:

$curl = curl_init ();
curl_setopt_array ($curl, array (
  CURLOPT_URL => $site_url
  CURLOPT_USERPWD => $site_public_key . ":" . $site_private_key,
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $post_data
 ));

$data = curl_exec ($curl);

if ($data === false)
{
  echo 'Error: ' . curl_error ($curl);
}

else
{
  echo 'Result: ' . $data;
}


curl_close ($curl);

这里是我的Java版本,所有认证变量和数据都在之前初始化:

try
{

    String site_authentication = site_public_key + ":" + site_private_key;
    String encoded_site_authentication = new String(new Base64().encode(site_authentication.getBytes())).replaceAll("[\n\r]", "");

    URL url = new URL (resource_uri);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    DataOutputStream dataOutputStream = null;
    connection.setRequestMethod("POST");  
    connection.setRequestProperty("Authorization", "Basic " +  encoded_site_authentication);
    connection.setDoOutput(true);
    connection.setReadTimeout(10000);
    connection.connect();
    connection.getInputStream();
    OutputStream output=connection.getOutputStream();
    output.write(post_data.getBytes());

    StringBuilder sb = new StringBuilder();
    String line = null;


    BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = rd.readLine()) != null) {
     sb.append(line);
}
    result = sb.toString();

}
catch (Exception e)
{
    e.printStackTrace();
}
out.println(result);

有些东西不起作用......我认为问题出在输出流上,但我找不到错误

感谢您的帮助

Mr_Leo

0 个答案:

没有答案