欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpClient的简单使用

程序员文章站 2022-04-06 16:44:23
...
public class MainActivity extends AppCompatActivity {

public String urlString = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1";

 @Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    
    setContentView(R.layout.activity_main);
    
    new Thread(){
    
        @Override
        
        public void run() {
        
            super.run();
            
            //联网工具类,DefaultHttpClient封装了请求操作
            
            DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
            
            //初始化请求方式,并把接口传入;
            
            HttpGet httpGet = new HttpGet(urlString);
            
//     HttpPost httpPost = new HttpPost(urlString);

            try {
            
                //执行httpGet操作;
                
                HttpResponse response = defaultHttpClient.execute(httpGet);
                
                int statusCode = response.getStatusLine().getStatusCode();
                
         		Log.e("wzq","statusCode::" +statusCode);
 	 // String sss = URLEncoder.encode("sss");

                if (statusCode == 200){
                
                    //entity包含服务器返回的数据
                    
                    HttpEntity entity = response.getEntity();
                    
                    //EntityUtils是专门处理操作entity中的数据的一个类;
                    
                    String jsonResult =  EntityUtils.toString(entity);
                    
                    Log.e("wzq",jsonResult);
                    
                }else {
                
                    //do nothing
                }
                
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("wzq","e:" +e.toString());
               String urlString = 	"http://api.expoon.com/AppNews/getNewsList/type/1/p/1";

            }
        }
    }.start();

}

}