Android学习--HttpUrlConnection+JSON应用实例

实例天气预报

步骤:

  1. 添加网络权限

     <uses-permission android:name="android.permission.INTERNET" />
  2. 设置布局视图,activity文件中绑定ID,设置按钮的点击事件,将API网址传值过来,设置输入框输入城市

  3. 创建MyTask类继承AsyncTask,设置三个参数
  4. 在doInbackground方法中,(找水源)创建URL,请求返回,(开水闸)设置openConnection,(建管道)InputStream,
  5. 判断网页返回码是否为200正确,如果网络正常且返回数据正常,我们才能创建,否则返回“network_failed”
  6. (建蓄水池蓄水)InputStreamReader,(水桶盛水)BufferReader
  7. 设置temp,判断当读取temp是否能读取,当他不为空的时候,提取值,否则直接退出
  8. 返回stringBuffer.toString(),返回到JSON数据
  9. 在onPostExcute方法中,判断如果网络返回码错误,提示网络连接失败,否则就正常返回,做JSON解析判断,区分是{}还是【】来定义是object还是array,获得各种风力温度
  10. 赋值

    视图代码展示

 <EditText
        android:id="@+id/city_et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/search_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查询"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="天气:"/>
        <TextView
            android:id="@+id/wind_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="温度:"/>
        <TextView
            android:id="@+id/temp_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="风力:"/>
        <TextView
            android:id="@+id/weather_tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>

activity代码演示:

public class Weather2Activity extends AppCompatActivity {
    private EditText cityET;
    private TextView weatherTV;
    private TextView windTV;
    private TextView tempTV;
    private Button searchBtn;
    private String API="https://free-api.heweather.com/s6/weather/now?key=73faf20c8cdc4935943a9703a9068b4f&location=";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wea);

        bindID();

        searchBtn.setOnClickListener(  new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MyTask().execute(API+cityET.getText().toString());
            }
        });
    }

    class MyTask extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... strings) {
            StringBuffer stringBuffer=new StringBuffer();
            try {
                URL url=new URL(strings[0]);//请求返回
                HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                InputStream inputStream=null;
                if (connection.getResponseCode()==200) {
                    inputStream=connection.getInputStream();//还有网络正常且返回数据正常,我们才能创建
                }else {
                    return "network_failed";
                }

                InputStreamReader reader=new InputStreamReader(inputStream);
                BufferedReader bufferedReader=new BufferedReader(reader);

                String temp=null;
                while ((temp=bufferedReader.readLine())!=null){
                    stringBuffer.append(temp);
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return stringBuffer.toString();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(s.equals("network_failed")){
                Toast.makeText(Weather2Activity.this,"连接失败",Toast.LENGTH_SHORT).show();
            }else {
                //JSON解析
                try {
                    JSONObject object=new JSONObject(s);
                    JSONArray array=object.getJSONArray("HeWeather6");
                    JSONObject object1=array.getJSONObject(0);
                    JSONObject newobject=object1.getJSONObject("now");
                    String wind=newobject.getString("cond_txt");
                    String weather=newobject.getString("wind_dir")+newobject.getString("wind_sc")+"级";
                    String tmp=newobject.getString("tmp");

                    //赋值
                    weatherTV.setText(weather);
                    windTV.setText( wind);
                    tempTV.setText(tmp);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void bindID() {
        cityET=findViewById(R.id.city_et);
        windTV=findViewById(R.id.wind_tv);
        tempTV=findViewById(R.id.temp_tv);
        weatherTV=findViewById(R.id.weather_tv);
        searchBtn=findViewById(R.id.search_btn);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android中使用JSON进行POST请求通信,可以使用HttpURLConnection或HttpClient来实现。以下是一个简单的示例,展示如何封装一个POST请求通信模块。 1. 首先,创建一个名为HttpUtils的类,并将其声明为单例模式,以便在整个应用程序中共享。 ```java public class HttpUtils { private static HttpUtils instance; private HttpUtils() {} public static synchronized HttpUtils getInstance() { if (instance == null) { instance = new HttpUtils(); } return instance; } // 实现发送POST请求的方法 public void sendPostRequest(String url, JSONObject postData, final OnResponseListener listener) { new Thread(new Runnable() { @Override public void run() { try { // 创建连接和设置请求参数 URL url = new URL(url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(5000); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); // 发送数据 OutputStream outputStream = connection.getOutputStream(); outputStream.write(postData.toString().getBytes()); outputStream.flush(); outputStream.close(); // 获取响应数据 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); inputStream.close(); // 回调响应结果 listener.onResponse(response.toString()); } else { listener.onError("请求失败:" + responseCode); } } catch (Exception e) { e.printStackTrace(); listener.onError("请求失败:" + e.getMessage()); } } }).start(); } } ``` 2. 创建一个名为OnResponseListener的接口,用于回调请求的响应结果。 ```java public interface OnResponseListener { void onResponse(String response); void onError(String error); } ``` 3. 在使用该模块时,可以调用sendPostRequest方法发送POST请求,并传入请求URL、JSON数据和OnResponseListener回调对象。 ```java HttpUtils.getInstance().sendPostRequest("http://example.com/api", jsonData, new OnResponseListener() { @Override public void onResponse(String response) { // 处理请求成功的响应结果 } @Override public void onError(String error) { // 处理请求失败的情况 } }); ``` 通过这个模块封装实例,可以方便地发送JSON格式的POST请求,并根据请求结果进行相应的处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值