[Socket]利用Android下的HttpClient发送GET && POST请求

上一篇写的是利用Jakarta下的org.apache.commons.的HttpClient发送GET和POST请求,但是Android的jar包已经集成了org.apache.http.client.HttpClient类,所以本文主要介绍Android下的HttpClient发送GET和POST请求:

 

以下为转帖:

本文将介绍Android SDK集成的Apache HttpClient模块。要注意的是,这里的Apache HttpClient模块是HttpClient 4.0(org.apache.http.*),而不是Jakarta Commons HttpClient 3.x(org.apache.commons.httpclient.*)。

在HttpClient模块中用到了两个重要的类:HttpGet和HttpPost。这两个类分别用来提交HTTP GET和HTTP POST请求。为了测试本节的例子,需要先编写一个Servlet程序,用来接收HTTP GET和

HTTP POST请求。读者也可以使用其他服务端的资源来测试本节的例子。

假设192.168.17.81是本机的IP,客户端可以通过如下的URL来访问服务端的资源:

http://192.168.17.81:8080/querybooks/QueryServlet?bookname=开发

在这里bookname是QueryServlet的请求参数,表示图书名,通过该参数来查询图书信息。

现在我们要通过HttpGet和HttpPost类向QueryServlet提交请求信息,并将返回结果显示在TextView组件中。

无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源。

1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。

2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。

3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。

如果使用HttpPost方法提交HTTP POST请求,还需要使用HttpPost类的setEntity方法设置请求参数。

本例使用了两个按钮来分别提交HTTP GET和HTTP POST请求,并从EditText组件中获得请求参数(bookname)值,最后将返回结果显示在TextView组件中。两个按钮共用一个onClick事件方法,

代码如下:

public void onClick(View view){
	    //读者需要将本例中的IP换成自己机器的IP  
	    String url = "http://192.168.17.81:8080/querybooks/QueryServlet";  
	    TextView tvQueryResult = (TextView) findViewById(R.id.tvQueryResult);  
	    EditText etBookName = (EditText) findViewById(R.id.etBookName);  
	    HttpResponse httpResponse = null;  
	    try{  
		switch (view.getId()){  
	            //  提交HTTP GET请求  
	            case R.id.btnGetQuery:  
	                //  向url添加请求参数  
	                url += "?bookname=" + etBookName.getText().toString();  
	                //  第1步:创建HttpGet对象  
	                HttpGet httpGet = new HttpGet(url);  
	                //  第2步:使用execute方法发送HTTP GET请求,并返回HttpResponse对象  
	                httpResponse = new DefaultHttpClient().execute(httpGet);  
	                //  判断请求响应状态码,状态码为200表示服务端成功响应了客户端的请求  
	                if (httpResponse.getStatusLine().getStatusCode() == 200){  
	                	//  第3步:使用getEntity方法获得返回结果  
	                	String result = EntityUtils.toString(httpResponse.getEntity());
	                	//  去掉返回结果中的"\r"字符,否则会在结果字符串后面显示一个小方格  
	                    tvQueryResult.setText(result.replaceAll("\r", ""));  
	                }  
	                break;  
	                //  提交HTTP POST请求  
	            case R.id.btnPostQuery:  
	                //  第1步:创建HttpPost对象  
	                HttpPost httpPost = new HttpPost(url);  
	                //  设置HTTP POST请求参数必须用NameValuePair对象  
	                List<NameValuePair> params = new ArrayList<NameValuePair>();  
	                params.add(new BasicNameValuePair("bookname", etBookName.getText(). toString()));  
	                //  设置HTTP POST请求参数  
	                httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));  
	                //  第2步:使用execute方法发送HTTP POST请求,并返回HttpResponse对象  
	                httpResponse = new DefaultHttpClient().execute(httpPost);  
	                if (httpResponse.getStatusLine().getStatusCode() == 200){  
	                    //  第3步:使用getEntity方法获得返回结果  
	                    String result = EntityUtils.toString(httpResponse.getEntity());  
	                    //  去掉返回结果中的"\r"字符,否则会在结果字符串后面显示一个小方格  
	                    tvQueryResult.setText(result.replaceAll("\r", ""));  
	                }  
	                break;  
	        }  
	    }catch (Exception e){  
	        tvQueryResult.setText(e.getMessage());
	    }  


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用Apache HttpClient库来发送HTTP请求,包括GETPOST等方式,也可以通过HttpClient发送HTTPS请求。使用HttpClient发送HTTPS请求需要添加SSL证书和设置SSL连接的相关参数。 以下是通过HttpClient发送GETPOST请求的示例代码: 1. 发送GET请求 ```java import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientTest { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); String url = "http://www.example.com/api?param1=value1&param2=value2"; HttpGet httpGet = new HttpGet(url); String response = null; try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { response = EntityUtils.toString(httpResponse.getEntity()); } System.out.println(response); } } ``` 2. 发送POST请求 ```java import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientTest { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); String url = "http://www.example.com/api"; HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); String requestBody = "{\"param1\":\"value1\",\"param2\":\"value2\"}"; httpPost.setEntity(new StringEntity(requestBody, "UTF-8")); String response = null; try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) { response = EntityUtils.toString(httpResponse.getEntity()); } System.out.println(response); } } ``` 如果需要发送HTTPS请求,则需要添加SSL证书和设置SSL连接的相关参数。具体可以参考以下示例代码: ```java import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class HttpClientTest { public static void main(String[] args) throws Exception { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslSocketFactory) .register("http", new PlainConnectionSocketFactory()) .build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connectionManager.setMaxTotal(200); connectionManager.setDefaultMaxPerRoute(20); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(5000) .setConnectTimeout(5000) .setConnectionRequestTimeout(5000) .build(); CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .build(); String url = "https://www.example.com/api?param1=value1&param2=value2"; HttpGet httpGet = new HttpGet(url); String response = null; try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { response = EntityUtils.toString(httpResponse.getEntity()); } System.out.println(response); } } ``` 需要注意的是,以上代码中的SSL证书验证方式为信任所有证书,不建议在生产环境中使用。建议根据实际情况设置合适的证书验证方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值