httpclient(Get方法)

来源:互联网 发布:linux 查看caffe版本 编辑:程序博客网 时间:2024/06/08 07:06
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);

        }

    }


需要build添加

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