我必須使用我已經生成的JSON字符串發出http Post請求。 我嘗試了不同的兩種不同的方法:使用JSON字符串在HTTP中的HTTP POST請求
1.HttpURLConnection
2.HttpClient
,但我從他們兩個相同的「無用」的結果。 到目前爲止我的代碼與HttpURLConnection的是:
public static void SaveWorkflow() throws IOException {
URL url = null;
url = new URL(myURLgoeshere);
HttpURLConnection urlConn = null;
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.connect();
DataOutputStream output = null;
DataInputStream input = null;
output = new DataOutputStream(urlConn.getOutputStream());
/*Construct the POST data.*/
String content = generatedJSONString;
/* Send the request data.*/
output.writeBytes(content);
output.flush();
output.close();
/* Get response data.*/
String response = null;
input = new DataInputStream (urlConn.getInputStream());
while (null != ((response = input.readLine()))) {
System.out.println(response);
input.close();
}
}
到目前爲止我的代碼與HttpClient的是:
public static void SaveWorkflow() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(myUrlgoeshere);
StringEntity input = new StringEntity(generatedJSONString);
input.setContentType("application/json;charset=UTF-8");
postRequest.setEntity(input);
input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
postRequest.setHeader("Accept", "application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
在哪裏產生JsonString是這樣的:
{"description":"prova_Process","modelgroup":"","modified":"false"}
的我得到的迴應是:
{"response":false,"message":"Error in saving the model. A JSONObject text must begin with '{' at 1 [character 2 line 1]","ids":[]}
有什麼想法嗎?
您是否嘗試過只是字符串轉換爲對象(解析JSON)中間沒有HTTP傳輸步驟? –
嘗試使用generatedJSONString.trim() – aquaraga
看起來像要使用RESTful web服務;您可能希望通過應用JAX-RS API來讓自己的生活變得非常簡單。 – Gimby