我正在尝试使用java发送HTTP POST请求。我能够发送一个简单的json消息但是当我尝试向json消息添加多个属性时,我得到了400个错误的请求响应。我试图使用Gson to_json来正确显示它。有没有人知道我哪里错了?
public boolean Record(String message, LevelType levelType)
{
try
{
URL url;
url = new URL(String.format("https://intake.opbeat.com/api/v1/organizations/%s/apps/%s/errors/", this.OrganizationId, this.AppId));
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty ("Authorization", "Bearer " + this.SecretToken);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
//write parameters
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
JsonObject test = new JsonObject();
test.addProperty("Application ", ApplicationName);
test.addProperty("Environment ", environment.name());
test.addProperty("error ", message);
String testAsJson = new Gson().toJson(test);
writer.write(testAsJson);
writer.flush();
writer.close();
// Get the response
int responseCode = conn.getResponseCode();
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
{
answer.append(line);
}
reader.close();
//Output the response
CustomLog.printlnVerbose(answer.toString());
}
catch (MalformedURLException ex)
{
CustomLog.println(ex);
}
catch (IOException ex)
{
CustomLog.println(ex);
}
//Send an http post to opbeat
return true;
}
}
答案 0 :(得分:0)
请将此文件保存在您的项目中:
码头-web.xml中
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN"
"http://jetty.mortbay.org/configure.dtd">
<Configure id="WebAppContext" class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="maxFormContentSize" type="int">800000</Set>
</Configure>
&#13;
maxFormContentSize =设置你想要的人数。
答案 1 :(得分:0)
我明白了。我需要做几件事。
更改&#34; writer.write(testAsJson)&#34; to&#34; writer.write(testAsJson.to_string)&#34;
添加第二个json对象时,而不是&#34; testAsJson.addProperty&#34;我需要使用&#34; testAsJson.add&#34;。
解决了我的错误并成功完成了POST请求。我非常感谢发布的答案!