post請求網路資料
//post請求
public static String httpPost(String str1, String str2) {
// http://apis.juhe.cn/cook/query ? key=&menu=蛋炒飯
try {
//設定url
URL url = new URL(str1);
//獲取HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//設定為post請求
connection.setRequestMethod("POST");
//使用寫入和讀取(post請求必須要寫這個倆)
connection.setDoOutput(true);
connection.setDoInput(true);
//
PrintWriter writer = new PrintWriter(connection.getOutputStream());
writer.write(str2);// key= &menu=蛋炒飯
writer.flush();
;//重新整理
//判斷是否成功
int code = connection.getResponseCode();
if (code == 200) {
//讀取資料
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "utf-8"));
//拼接字串
StringBuilder builder = new StringBuilder();
String s = "";
//讀取資料
while ((s = reader.readLine()) != null) {
//拼接字串
builder.append(s);
}
return builder.toString();
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}在這裡插入程式碼片