HttpGet 请求

 

 

import java.net.HttpURLConnection;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

import java.util.List;



import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;



import com.google.gson.Gson;

import com.google.gson.JsonElement;

import com.google.gson.JsonParser;

import com.google.gson.reflect.TypeToken;



public class Test {



    /**

     * @param args

     */

    public static void main(String[] args) {



        HttpClient httpClient = new DefaultHttpClient();

        String strResult = "";

        try {

            Date date = new Date();

            Calendar cal = Calendar.getInstance();

            cal.setTime(date);

            cal.add(Calendar.DATE, -1);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            String dateStr = sdf.format(cal.getTime());

            String url = "http://192.168.0.1:1234/test/getData?uid=12&date="

                    + dateStr;

            /* 建立HttpGet对象 */

            HttpGet httpget = new HttpGet(url);

            httpget.addHeader("request-key", "test-007"); // 请求访问key



            /* 发送请求并等待响应 */

            HttpResponse httpResponse = httpClient.execute(httpget);

            if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {

                /* 读返回数据 */

                strResult = EntityUtils.toString(httpResponse.getEntity());



                /* json字符串转 list<T> */

                JsonParser jsonparer = new JsonParser();

                JsonElement je = null;

                je = jsonparer.parse(strResult);

                Object ob = je.getAsJsonObject().get("data");

                Gson gson = new Gson();

                List<TestPojo> picInfoList = gson.fromJson(ob.toString(),

                        new TypeToken<List<TestPojo>>() {

                        }.getType());



                for (TestPojo temp : picInfoList) {

                    System.out.println(temp.getTime());

                }



                System.out.println("--strResult:" + strResult);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            // 关闭连接 ,释放资源

            httpClient.getConnectionManager().shutdown();

        }

    }

}

 

你可能感兴趣的:(http)