目前我正在试图通过以下的fliptop说明使用的API。 api的描述指定它必须使用json输入,因此,我创建了json对象并将其转换为字符串我自己。然而,当我尝试使用find_contact API,HTTP响应得到HttpPost请求不发送正确的JSON数据
{ “参数”:500}
,而不是正确的数据像
{ “账”: { “site_key”: “... ” “SEAT_ID”:“ ...”, “org_id”: “”, “许可证”:{ ... }。
我尝试做文档网站上的一些测试(点击任何先进的API,你会看到它)与不正确输入发送请求,它给了我同样的反应体{“参数”:500}。因此,我认为我的请求实体可能有问题。
这是我的代码。谁能告诉我它有什么问题?
import java.io.BufferedReader;
import java.io.InputStreamReader;
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.simple.JSONArray;
import org.json.simple.JSONObject;
public class Test {
// Generate json string
// {"contacts": [ { "email": "[email protected]", "title":"CEO", "company":"Fliptop", "address":"San Francisco"} ] }
public static String jsonString() {
JSONObject obj1 = new JSONObject();
obj1.put("email", "[email protected]");
obj1.put("title", "CEO");
obj1.put("company", "Fliptop");
obj1.put("address", "San Francisco");
JSONArray list1 = new JSONArray();
list1.add(obj1);
JSONObject obj2 = new JSONObject();
obj2.put("contacts", list1);
System.out.println(obj2.toJSONString());
return obj2.toJSONString();
}
public static void find_contact() {
HttpClient httpClient = new DefaultHttpClient();
try {
//you will need api key here!!
HttpPost request = new HttpPost("http://api.fliptop.com/s2/v1/find_contact?api_key=xxxxxxxxxxxxxxxxxxxxxx");
StringEntity params = new StringEntity(jsonString(),"UTF-8");
params.setContentType("application/json; charset=UTF-8");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String result = "";
String line;
while ((line = rd.readLine()) != null) {
result += line;
}
System.out.println(result);
rd.close();
System.out.println("status:" + response.getStatusLine());
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
find_contact();
}
}
更新:
我跟戴夫的建议,并通过Wireshark的检查请求。该请求表明为POST请求,并且数据是纯文本/具有以下内容
JSON = {“接触”:[{“电子邮件”:“[email protected]”,“标题“:”CEO“,”公司“:”Fliptop“,”地址“:”旧金山“}]}。
我不是一个网络专家,但请求似乎没什么问题。不过,我搞不清这是怎么回事...
你检查线,看看你实际发送? –
我真的不明白你说什么......我尝试把它回InputStreamReader和随后的BufferedReader读取实体。实体本身的字符串是正确的。 – cwhsu
我在说“通过检查正在发送的请求,检查你的假设是否实际发送到了服务器。 –