基于post请求的 android studio天气预报程序的源代码并且包含详细注释
时间: 2024-04-20 13:23:59 浏览: 11
当然可以!以下是一个基于POST请求的Android Studio天气预报程序的源代码,包含详细注释:
```java
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeatherActivity extends AppCompatActivity {
private EditText cityEditText;
private Button searchButton;
private TextView resultTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
// 初始化界面元素
cityEditText = findViewById(R.id.cityEditText);
searchButton = findViewById(R.id.searchButton);
resultTextView = findViewById(R.id.resultTextView);
searchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String city = cityEditText.getText().toString();
// 执行异步任务
new WeatherTask().execute(city);
}
});
}
private class WeatherTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String city = params[0];
String apiUrl = "http://api.weatherapi.com/v1/current.json";
String apiKey = "YOUR_API_KEY"; // 替换为你的API key
try {
// 创建URL对象
URL url = new URL(apiUrl);
// 创建HTTP连接对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
// 构建请求参数
JSONObject jsonParam = new JSONObject();
jsonParam.put("key", apiKey);
jsonParam.put("q", city);
// 发送请求
OutputStream os = conn.getOutputStream();
os.write(jsonParam.toString().getBytes());
os.flush();
os.close();
// 获取响应结果
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
br.close();
// 解析JSON结果
JSONObject jsonResult = new JSONObject(sb.toString());
String weather = jsonResult.getJSONObject("current").getString("condition");
return weather;
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
resultTextView.setText(result);
} else {
resultTextView.setText("Failed to get weather information.");
}
}
}
}
```
这段代码实现了一个天气预报程序,用户可以输入城市名字,点击搜索按钮后会通过POST请求向天气API发送请求,并获取返回的天气信息。请注意,你需要替换代码中的`YOUR_API_KEY`为你自己的API密钥,以便从天气API获取数据。此外,还要确保你的Android设备具有网络连接权限。
希望这段代码对你有所帮助!如果有任何问题,请随时问我。