HTTPclient+json

来源:互联网 发布:python编写exe程序 编辑:程序博客网 时间:2024/06/16 02:44
packagecom.example.testjsonandget;
importjava.io.BufferedReader;
importjava.io.InputStreamReader;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.HttpStatus;
importorg.apache.http.NameValuePair;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.client.params.HttpClientParams;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.params.BasicHttpParams;
importorg.apache.http.params.HttpConnectionParams;
importorg.apache.http.params.HttpParams;
importorg.json.JSONArray;
importorg.json.JSONObject;
 
importandroid.app.Activity;
importandroid.os.Bundle;
 
publicclass MainActivity extendsActivity {
    privatefinal String uriString="your url";
    @Override
    publicvoid onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //服务器返回的JSON数据
        JSONObject jsonObject=this.getJSONObjectByGet();
        try{
            //从JSON中得到字符串
            String apiString=jsonObject.getString("api");
            String countString=jsonObject.getString("count");
            System.out.println("apiString="+apiString+",countString="+countString);
            //从JSON中得到JSONArray,并且遍历
            JSONArray jsonArray=jsonObject.getJSONArray("data");
            for(inti = 0; i < jsonArray.length(); i++) {
                JSONObject everyJsonObject=jsonArray.getJSONObject(i);
                String category_id=everyJsonObject.getString("category_id");
                String category_name=everyJsonObject.getString("category_name");
                String category_rgb=everyJsonObject.getString("category_rgb");
                String category_news_count=everyJsonObject.getString("category_news_count");
                System.out.println("category_id="+category_id+",category_name="+category_name+
                ",category_rgb="+category_rgb+",category_news_count="+category_news_count);
                System.out.println("=====================================================");
            }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
 
    //得到HttpClient
    publicHttpClient getHttpClient(){
        HttpParams mHttpParams=newBasicHttpParams();
        //设置网络链接超时
        //即:Set the timeout in milliseconds until a connection is established.
        HttpConnectionParams.setConnectionTimeout(mHttpParams, 20*1000);
        //设置socket响应超时
        //即:in milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setSoTimeout(mHttpParams, 20*1000);
        //设置socket缓存大小
        HttpConnectionParams.setSocketBufferSize(mHttpParams, 8*1024);
        //设置是否可以重定向
        HttpClientParams.setRedirecting(mHttpParams, true);
         
        HttpClient httpClient=newDefaultHttpClient(mHttpParams);
        returnhttpClient;
    }
     
    //得到JSONObject(Get方式)
    publicJSONObject getJSONObjectByGet(){
        JSONObject resultJsonObject=null;
        if("".equals(uriString)||uriString==null) {
            returnnull;
        }
        HttpClient httpClient=this.getHttpClient();
        StringBuilder urlStringBuilder=newStringBuilder(uriString);
        StringBuilder entityStringBuilder=newStringBuilder();
        //利用URL生成一个HttpGet请求
        HttpGet httpGet=newHttpGet(urlStringBuilder.toString());
        BufferedReader bufferedReader=null;
        HttpResponse httpResponse=null;
        try{
            //HttpClient发出一个HttpGet请求
            httpResponse=httpClient.execute(httpGet);      
        catch(Exception e) {
            e.printStackTrace();
        }
        //得到httpResponse的状态响应码
        intstatusCode=httpResponse.getStatusLine().getStatusCode();
        if(statusCode==HttpStatus.SC_OK) {
            //得到httpResponse的实体数据
            HttpEntity httpEntity=httpResponse.getEntity();
            if(httpEntity!=null) {
                try{
                    bufferedReader=newBufferedReader
                    (newInputStreamReader(httpEntity.getContent(), "UTF-8"), 8*1024);
                    String line=null;
                    while((line=bufferedReader.readLine())!=null) {
                        entityStringBuilder.append(line+"/n");
                    }
                    //利用从HttpEntity中得到的String生成JsonObject
                    resultJsonObject=newJSONObject(entityStringBuilder.toString());
                catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
        returnresultJsonObject;
    }
     
    //----------------------------------------以下为POST请求
    //准备进行POST请求的参数,一般而言将这些参数封装在HashMap中
    publicJSONObject save(String title, String timelength) throwsException{
        Map<String,String> paramsHashMap = newHashMap<String, String>();
        paramsHashMap.put("title", title);
        paramsHashMap.put("timelength", timelength);
        paramsHashMap.put("method""save");
        String path = "your url";
        returngetJSONObjectByPost(path, paramsHashMap, "UTF-8");
    }
    //得到JSONObject(Post方式)
    //此方法此处未调用测试
    publicJSONObject getJSONObjectByPost(String path,Map<String, String> paramsHashMap, String encoding) {
        JSONObject resultJsonObject = null;
        List<NameValuePair> nameValuePairArrayList = newArrayList<NameValuePair>();
        // 将传过来的参数填充到List<NameValuePair>中
        if(paramsHashMap != null&& !paramsHashMap.isEmpty()) {
            for(Map.Entry<String, String> entry : paramsHashMap.entrySet()) {
                nameValuePairArrayList.add(newBasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
         
        UrlEncodedFormEntity entity = null;
        try{
            // 利用List<NameValuePair>生成Post请求的实体数据
            // 此处使用了UrlEncodedFormEntity!!!
            entity = newUrlEncodedFormEntity(nameValuePairArrayList, encoding);
            HttpPost httpPost = newHttpPost(path);
            // 为HttpPost设置实体数据
            httpPost.setEntity(entity);
            HttpClient httpClient = this.getHttpClient();
            // HttpClient发出Post请求
            HttpResponse httpResponse = httpClient.execute(httpPost);
            if(httpResponse.getStatusLine().getStatusCode() == 200) {
                // 得到httpResponse的实体数据
                HttpEntity httpEntity = httpResponse.getEntity();
                if(httpEntity != null) {
                    try{
                        BufferedReader bufferedReader = newBufferedReader(
                        newInputStreamReader(httpEntity.getContent(),"UTF-8"), 81024);
                        StringBuilder entityStringBuilder = newStringBuilder();
                        String line = null;
                        while((line = bufferedReader.readLine()) != null) {
                            entityStringBuilder.append(line + "/n");
                        }
                        // 利用从HttpEntity中得到的String生成JsonObject
                        resultJsonObject = newJSONObject(entityStringBuilder.toString());
                    catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        catch(Exception e) {
            e.printStackTrace();
        }
        returnresultJsonObject;
    }
}
0 0