javascript
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());
/*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":[]}
有什么想法嗎?
總結
以上是生活随笔為你收集整理的java url json字符串_JAVA中带有JSON字符串的HTTP POST请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 娃哈哈矿泉水图片(娃哈哈桶装水是矿泉水还
- 下一篇: 朴志效(说一说朴志效的简介)