HttpClient请求连接网络

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

import static android.content.ContentValues.TAG;

/**
 * httpClient-- apche 基金会维护的请求网络的工具;
 */


public class NetWorkUtils {
    public  String tag = "NetWorkUtils";
    /**
     * apache
     *
     * @param jsonUrl
     * @return
     */
    public String getJsonByHttpClientGet(String jsonUrl) {

        //获取httpclient对象
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        //准备一个get请求
        HttpGet httpGet = new HttpGet(jsonUrl);
        try {
            //得到服务器返回的数据;
            HttpResponse response = defaultHttpClient.execute(httpGet);
            //得到状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode ==200){
                //entiry 里面封装的数据;
                HttpEntity entity = response.getEntity();
                //这个result就是json字符串,剩下的就是解析工作了;
                String result = EntityUtils.toString(entity);
                Log.e(TAG, "result: "+result );
            }


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

        return null;

    }
}

你可能感兴趣的:(HttpClient请求连接网络)