httpclientrequestforget client方法 过期了 但是还用

来源:互联网 发布:c语言如何产生随机数 编辑:程序博客网 时间:2024/04/28 18:11

在build.gradle里加这句话

android {    useLibrary 'org.apache.http.legacy'}


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.example.httpclientrequestforget.utils.StreamTools;

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 java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);





    }

    public void btnHttpClientRequest(View view){

        new Thread(){
            @Override
            public void run() {
                super.run();

                try {
                    httpClientRequestForGet();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();


    }


    /**
     * 使用HttpClient这个api请求网络数据
     * 请求方式:GET
     * android 6.0以后,google不再推介使用这种方式,推介HttpURLConnection
     */
    private void httpClientRequestForGet() throws Exception{

        //1.打开浏览器
        HttpClient httpClient = new DefaultHttpClient();
        //2.填下地址
        HttpGet httpGet = new HttpGet("http://apis.juhe.cn/cook/query.php?menu=秘制红烧肉&key=ff00d7339861c7fd7d5b54b16b76422a");
        //3.敲回车
        HttpResponse response = httpClient.execute(httpGet);

        //4.等待服务器响应,获得响应状态码
        int code = response.getStatusLine().getStatusCode();
        if(code == 200){
            //5.获取服务器响应的内容
            InputStream is = response.getEntity().getContent();

            String json = StreamTools.readFromNetWork(is);

            System.out.println("httpclient : "+json);

        }



    }





}

阅读全文
0 0