2

How can I convert this java code to 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();

When I try following php code I get The server refused this request because the request entity is in a format not supported by the requested resource for the requested method (). error

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

    echo curl_exec($curl);

1 Answer 1

2

Try setting the content type header with your curl:

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

And here is an example of preparing json:

$data = array(
    'name' => 'alex',
    'value' => '100'
);
$json_data = json_encode($data); // {"name":"alex","value":"100"}
Sign up to request clarification or add additional context in comments.

3 Comments

mimeType is a java variable which contain "application/json". In php when I put CURLOPT_HTTPHEADER array("Content-Type: application/json");
It gives me error The request sent by the client was syntactically incorrect ().
@SiddharthNagar your json data may be not correct in format. check how you can use correct formatted json from my updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.