2014-03-28 82 views
1

如何將此java代碼轉換爲php。將java rest請求轉換爲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

嘗試用你的捲曲設置內容類型標題:

$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"} 
+0

mime類型是包含Java變量「應用程序/ JSON」。在PHP中,當我把CURLOPT_HTTPHEADER數組(「Content-Type:application/json」); –

+0

它給我錯誤客戶端發送的請求在語法上不正確()。 –

+0

@SiddharthNagar您的json數據格式可能不正確。檢查如何從我更新的答案中使用正確的格式化json。 –