欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

java json post請(qǐng)求參數(shù)

本文將介紹如何使用Java發(fā)送帶有JSON參數(shù)的POST請(qǐng)求。

首先需要導(dǎo)入相關(guān)依賴:

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

通過GSON庫(kù)將JSON轉(zhuǎn)化為Java對(duì)象:

String jsonParam = "{\"name\": \"John\", \"age\": 25}";
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonParam, JsonObject.class);

發(fā)送POST請(qǐng)求時(shí),需要將JSON參數(shù)轉(zhuǎn)化為字符串并設(shè)置到請(qǐng)求體中:

String apiUrl = "http://example.com/api";
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = jsonObject.toString();
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();

其中,setDoOutput(true)表示可以向請(qǐng)求體中寫入數(shù)據(jù),setRequestMethod("POST")表示請(qǐng)求方法為POST。

最后不要忘記關(guān)閉輸入輸出流和斷開連接。