大家好我是一名初级php开发人员我正在努力将java代码转换为php ..对Java api命中并正确获取响应现在我正试图在php中使用curl http post这是我在我的任务软件公司PLZ帮帮我
我要告诉你我的java代码是否正常工作然后我的PHP代码无效并且没有解析params到那个api所以请指导我
这是我的Java代码 这是正常的,我想从php
做同样的工作import java.io.*;
import java.util.jar.JarException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;
class MyCode{
public static void main(String[] args) throws JarException, JSONException
{
testCustomerApiIsExposed();
}
public static void testCustomerApiIsExposed() throws JarException, JSONException {
try {
@SuppressWarnings("deprecation")
HttpClient c = new DefaultHttpClient();
HttpPost p = new
HttpPost("http://link");
String payload = "{id:\"" + 1 + "\"," + "method:\"" + "customerApi.getApiToken" + "\", params:[\"teabonezenminddemo1partner@gmail.com\", \"demo1234!\", \"\", \"\", \"\", \"\", \"\", false, \"\", \"\"" + "]}";
String mimeType="";
/*There is something here. What constructor are we really calling here? */
// p.setEntity(new StringEntity( payload,ContentType.create("application/json")));
p.setEntity(new StringEntity(payload));
HttpResponse r = c.execute(p);
BufferedReader reader = new BufferedReader(new InputStreamReader(r.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener("[" + builder.toString() + "]");
JSONArray finalResult = new JSONArray(tokener);
JSONObject o = finalResult.getJSONObject(0);
//Getting names of the JSON object here
System.out.println(o.names());
String apiToken = (String) o.get("result");
System.out.println(apiToken);
}
catch(IOException e) {
System.out.println(e);
}
}
}
现在我在php上编码,但是没有得到回复检查它并指导我使用curl http post和getApiToken方法帮助我解决这个问题我非常紧张。
这是我的php代码
<?php
$data = array(params);
$ch = curl_init('http://link');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
?>
答案 0 :(得分:0)
您正在从您的Java代码发布JSON。所以在PHP中也使用json(确保格式正常):
$payload = "{params}";
卷曲选项将是
// as you are posting JSON, so tell server that you are sending json
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
// Let server know that you are doing HTTP POST request
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
使用这些,我得到了样本回复:
{"id":"1","result":"results"}