将java rest请求转换为php代码

时间:2014-03-28 13:15:10

标签: java php rest curl

如何将此java代码转换为php。

server = new URL(url);
    HttpURLConnection urlConnection  = (HttpURLConnection) server.openConnection() ;
    urlConnection.setRequestMethod( method );
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setRequestProperty("Content-Type",mimeType );
    if( requestParameter != null)
    {
        CyberoamLogger.appLog.debug(MODULE+":"+METHOD+"Request parameter: "+requestParameter.toString());
        out = new BufferedWriter( new OutputStreamWriter( urlConnection.getOutputStream() ) );
        out.write(requestParameter.toString());
        out.flush();
        out.close() ;
    }

    urlConnection.connect();    
    strbuf = new StringBuffer();            
     is= urlConnection.getInputStream()   ;   
    byte[] buffer = new byte[1024 * 4];        
    int n = 0;
    while (-1 != (n = is.read(buffer)))
        strbuf.append(new String(buffer, 0, n));
    is.close();
    strResponse=strbuf.toString();
    CyberoamLogger.appLog.debug(MODULE+METHOD+ " WS Responce in String  : "+strResponse);
    urlConnection.disconnect();

当我尝试关注php代码时,我得到服务器拒绝了此请求,因为请求实体所采用的方法所请求的资源不支持该格式()。错误

$curl = curl_init();
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_URL, $url);

    echo curl_exec($curl);

1 个答案:

答案 0 :(得分:1)

尝试使用curl设置内容类型标题:

$mimeType = "application/json";
curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-Type: $mimeType"));
// equivalent to your java urlConnection.setRequestProperty("Content-Type",mimeType );

以下是准备json的一个例子:

$data = array(
    'name' => 'alex',
    'value' => '100'
);
$json_data = json_encode($data); // {"name":"alex","value":"100"}