android开发学习笔记(一)分别通过GET和POST请求从服务器端获取数据

最近学习从服务器获取数据并且解析,做了一些笔记。
android上发送请求的方式有两种,這里主要使用HttpURLConnection, 另一种不做考虑。

通过POST方式

发送请求的工具类

public class HttpUrl {

public static void sendhttpRequest(final String address, final HttpCallbackListener listener) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection httpURLConnection = null;
           try {

                URL url =new URL(address);
               httpURLConnection = (HttpURLConnection)url.openConnection();
               httpURLConnection.setRequestMethod("POST");
               httpURLConnection.setConnectTimeout(8000);
               httpURLConnection.setReadTimeout(8000);
               httpURLConnection.setDoInput(true);
               httpURLConnection.setDoOutput(true);

               PrintWriter pw = new PrintWriter(httpURLConnection.getOutputStream());

               pw.print("username=123");
               pw.flush();
               pw.close();

               InputStream in = httpURLConnection.getInputStream();
               BufferedReader reader = new BufferedReader(new InputStreamReader(in));
               StringBuilder response = new StringBuilder();
               String line;
               while ((line = reader.readLine()) != null) {
                   response.append(line);
               }
               if (listener != null){
                   listener.onFinsh(response.toString());
               }



            } catch (Exception e) {
        if(listener != null){
            listener.onError(e);
        }
    } finally {

        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }





        }

        }
    }).start();
}

}

依赖第三方库okhttp


public class MyHttp{

public static void  send(String address,okhttp3.Callback callback){
    OkHttpClient client = new OkHttpClient();
    RequestBody requestBody = new FormBody.Builder().add("username","123").build();
    Request request = new Request.Builder().url(address).post(requestBody).build();


    client.newCall(request).enqueue(callback);
}

}

通过GET

public class MyHttp{

public static void  send(String address,okhttp3.Callback callback){
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder().url(address).build();

    client.newCall(request).enqueue(callback);
}

}

参考了网上的资料,解析json的代码

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final List> ListData = getListData();
        SimpleAdapter ListAdapter = new SimpleAdapter(this, ListData, R.layout.list_view,
                new String[]{"name"},
                new int[]{R.id.name});

        ListView list = (ListView) findViewById(R.id.listview);
        list.setAdapter(ListAdapter);
      /*  list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {

               // Toast.makeText(MainActivity.this,   ListData.get(position).get("name").toString() ,Toast.LENGTH_LONG).show();
                Intent intent = new Intent(MainActivity.this,infoActivity.class);
                intent.putExtra("weather_id",ListData.get(position).get("weather_id").toString());
                startActivity(intent);
            }
        });*/

    }

   /*private List> getListData() {
        final List> Data = new ArrayList>();

        MyHttp.send("url", new okhttp3.Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String retStr = response.body().string();

                try {
                    JSONArray jsonArray = new JSONArray(retStr);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);

                        {
                            HashMap hashMap = new HashMap();
                            hashMap.put("name", jsonObject.getString("username"));
                           // hashMap.put("id", jsonObject.getString("id"));
                           // hashMap.put("weather_id", jsonObject.getString("weather_id"));

                            Data.add(hashMap);
                        }
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });


        return Data;
    }
}*/
  private List> getListData() {
        final List> Data = new ArrayList>();
        HttpUrl.sendhttpRequest("url", new HttpCallbackListener() {
            @Override
            public void onFinsh(String responsedata) {

                try {
                    JSONArray jsonArray = new JSONArray(responsedata);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        ;
                        {
                            HashMap hashMap = new HashMap();
                            hashMap.put("name", jsonObject.getString("username"));

                            Data.add(hashMap);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

                @Override
            public void onError(Exception e) {

            }
        });

        return Data;

    }
}






你可能感兴趣的:(android)