27.httpClien提交数据

本文介绍如何使用HttpClient进行GET和POST请求的步骤,并提供了一个具体的Android应用程序示例,演示了如何通过UI输入用户名和密码,然后使用HttpClient框架进行提交。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。 
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接

布局文件

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/et_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="请输入用户名" />
    <EditText
        android:id="@+id/et_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="请输入密码" />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="get"
        android:text="get方式提交"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="post"
        android:text="post方式提交"
        />

</RelativeLayout>

逻辑代码

MainActivity.java



import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg){
			Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
		}
	};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }



    public void get(View v){
    	
    	EditText et_name = (EditText) findViewById(R.id.et_name);
    	EditText et_pass = (EditText) findViewById(R.id.et_pass);
    	
    	final String name = et_name.getText().toString();
    	final String pass = et_pass.getText().toString();
    	
    	Thread t = new Thread(){
    		
    		@Override
    		public void run(){
    			final String path = "http://192.168.0.102/web2/servlet/LoginServlet?name=" + URLEncoder.encode(name) + "&pass=" + pass;
    	    	//使用httpClient框架实现get提交
    	    	//1.获取httpClient对象
    	    	HttpClient hc = new DefaultHttpClient();
    	    	
    	    	//2.创建httpGet对象,参数是网址
    	    	HttpGet hg = new HttpGet(path);
    	    	
    	    	//3.使用客户端对象,把get请求发送出去
    	    	try {
    				HttpResponse hr = hc.execute(hg);
    				//拿到状态行
    				StatusLine sl = hr.getStatusLine();
    				if(sl.getStatusCode() == 200){
    					HttpEntity he = hr.getEntity();
    					//拿到实体中的内容,是服务器返回的输入流
    					InputStream is = he.getContent();
    					String text = Utils.getTextFromStream(is);
    					
    					//刷新主线程显示text
    					Message msg = handler.obtainMessage();
    					msg.obj = text;
    					
    					handler.sendMessage(msg);
    				}
    			} catch (ClientProtocolException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    	};
    	t.start();

    	
    }
    
    public void post(View v){
    	EditText et_name = (EditText) findViewById(R.id.et_name);
    	EditText et_pass = (EditText) findViewById(R.id.et_pass);
    	
    	final String name = et_name.getText().toString();
    	final String pass = et_pass.getText().toString();
    	
    	
    	Thread t = new Thread(){
    		
    		@Override
    		public void run(){
    			final String path = "http://192.168.0.102/web2/servlet/LoginServlet";
    	    	//创建客户端对象
    	    	HttpClient hc = new DefaultHttpClient();
    	    	//创建post请求对象
    	    	HttpPost hp = new HttpPost(path);
    	    	
    	    	//封装form表单提交的数据
    	    	BasicNameValuePair bnvp1 = new BasicNameValuePair("name", name);
    	    	BasicNameValuePair bnvp2 = new BasicNameValuePair("pass", pass);
    	    	//BasicNameValuePair放入集合中
    	    	List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
    	    	parameters.add(bnvp1);
    	    	parameters.add(bnvp2);
    			try {
    				//把集合传给实体对象
    				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
    		    	//设置post请求对象的额事体,把提交的对象封装在post请求的输出流中
    		    	hp.setEntity(entity);
    		    	//3.使用客户端发送post请求
    				HttpResponse hr = hc.execute(hp);
    				if(hr.getStatusLine().getStatusCode() == 200){
    					InputStream is = hr.getEntity().getContent();
    					String text = Utils.getTextFromStream(is);
    					
    					//刷新主线程显示text
    					Message msg = handler.obtainMessage();
    					msg.obj = text;
    					
    					handler.sendMessage(msg);
    					
    				}
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    	};
    	t.start();
    	
    }
    
}

Utils.java

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Utils {
	
	public static String getTextFromStream(InputStream is){
		
		byte[] b = new byte[1024];
		int len = 0;
		//创建字节输出流,读取输入流的文本数据时,同时把数据写入到输出流
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			while((len = is.read(b)) != -1){
				bos.write(b, 0, len);
			}
			//把字节数组输出流里面的数据,转换成字节数组
			String text = new String(bos.toByteArray());
			return text;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}

 

 

 

 

在 Feign 中使用 HttpClient 连接池可以提高性能和资源利用率,避免重复创建和关闭连接。下面是整合的步骤: 1. 添加依赖 在 pom.xml 中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.12</version> </dependency> ``` 2. 配置 HttpClient 在 Spring Boot 中,可以使用 HttpClientBuilder 来构建 HttpClient,并配置连接池参数: ```java @Configuration public class HttpClientConfig { @Value("${httpclient.max-total}") private int maxTotal; @Value("${httpclient.default-max-per-route}") private int defaultMaxPerRoute; @Bean public CloseableHttpClient httpClient() { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(maxTotal); connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute); return HttpClientBuilder.create() .setConnectionManager(connectionManager) .build(); } } ``` 其中,maxTotal 表示连接池最大连接数,defaultMaxPerRoute 表示每个路由(域名)最大连接数。 3. 配置 Feign 在 Feign 中配置 HttpClient,需要实现 HttpClient 的 Client 接口,具体如下: ```java public class HttpClientFeignClient implements Client { private final CloseableHttpClient httpClient; public HttpClientFeignClient(CloseableHttpClient httpClient) { this.httpClient = httpClient; } @Override public Response execute(Request request, Request.Options options) throws IOException { HttpClientContext context = HttpClientContext.create(); HttpUriRequest httpUriRequest = toHttpUriRequest(request); CloseableHttpResponse httpResponse = httpClient.execute(httpUriRequest, context); return toResponse(httpResponse); } private HttpUriRequest toHttpUriRequest(Request request) { String method = request.method(); String url = request.url(); Request.Body body = request.body(); HttpEntityEnclosingRequestBase httpUriRequest; switch (method) { case "GET": httpUriRequest = new HttpGet(url); break; case "POST": httpUriRequest = new HttpPost(url); break; case "PUT": httpUriRequest = new HttpPut(url); break; case "DELETE": httpUriRequest = new HttpDelete(url); break; default: throw new UnsupportedOperationException("unsupported http method: " + method); } if (body != null) { httpUriRequest.setEntity(new ByteArrayEntity(body.asBytes())); } return httpUriRequest; } private Response toResponse(CloseableHttpResponse httpResponse) throws IOException { int statusCode = httpResponse.getStatusLine().getStatusCode(); String reasonPhrase = httpResponse.getStatusLine().getReasonPhrase(); Map<String, Collection<String>> headers = new HashMap<>(); for (Header header : httpResponse.getAllHeaders()) { String name = header.getName(); String value = header.getValue(); headers.computeIfAbsent(name, k -> new ArrayList<>()).add(value); } Response.Builder builder = Response.builder() .status(statusCode) .reason(reasonPhrase) .headers(headers); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); byte[] bodyData = ByteStreams.toByteArray(inputStream); builder.body(bodyData); } return builder.build(); } } ``` 最后,在 Feign 的配置类中,使用上述实现类作为 Client: ```java @Configuration public class FeignConfig { @Autowired private CloseableHttpClient httpClient; @Bean public Client feignClient() { return new HttpClientFeignClient(httpClient); } } ``` 这样就完成了 Feign 整合 HttpClient 连接池的配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值