1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java url json字符串_JAVA中带有JSON字符串的HTTP POST请求

java url json字符串_JAVA中带有JSON字符串的HTTP POST请求

时间:2022-01-30 13:12:18

相关推荐

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

有什么想法吗?

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。