天天看點

java url json字元串_JAVA中帶有JSON字元串的HTTP POST請求

我必須使用已經生成的JSON字元串發出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());

String content = generatedJSONString;

output.writeBytes(content);

output.flush();

output.close();

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":[]}

有什麼想法嗎?