2014-03-28 1 views
1

으로 변환이 Java 코드를 어떻게 PHP로 변환 할 수 있습니까? 나는 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(); 

나는 요청 엔티티가 아니라 요구받은 method의 자원이 지원되는 형식()에 있기 때문에 서버가이 요청을 거부 얻을. 오류

$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

mimeType를 포함 자바 변수 "응용 프로그램/json ". PHP에서는 내가 CURLOPT_HTTPHEADER 배열을 넣어 ("Content-Type : application/json"); –

+0

오류가 발생했습니다. 클라이언트가 보낸 요청이 구문 상 올바르지 않습니다(). –

+0

@SiddharthNagar json 데이터가 형식이 올바르지 않을 수 있습니다. 업데이트 된 답변에서 올바른 형식의 json을 어떻게 사용할 수 있는지 확인하십시오. –

관련 문제