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

HTTPClient使用

程序员文章站 2024-03-24 14:43:28
...

网址:
https://blog.csdn.net/gladiator0975/article/details/49177959

studio添加的依赖
android {
useLibrary ‘org.apache.http.legacy’
}
post的方法
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(“http://cnivi.com.cn/login”);
post.setEntity(reqEntity);
post.setConfig(requestConfig);
HttpResponse response = client.execute(post);

    if (response.getStatusLine().getStatusCode() == 200) {  
        HttpEntity resEntity = response.getEntity();  
        String message = EntityUtils.toString(resEntity, "utf-8");  
        System.out.println(message);  
    } else {  
        System.out.println("请求失败");  
    }  

get方法
首先需要先创建一个DefaultHttpClient的实例

HttpClient httpClient=new DefaultHttpClient();
先创建一个HttpGet对象,传入目标的网络地址,然后调用HttpClient的execute()方法即可:

HttpGet HttpGet=new HttpGet(“http://www.baidu.com”);

httpClient.execute(httpGet);

If(httpResponse.getStatusLine().getStatusCode()==200){
//请求和响应都成功了
HttpEntityentity=HttpResponse.getEntity();//调用getEntity()方法获取到一个HttpEntity实例
Stringresponse=EntityUtils.toString(entity,”utf-8”);//用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
}

相关标签: HTTPClient使用