httpClient post的使用

package com.example.day03;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Entity;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

private EditText input;
private Button button;
private TextView info;

private final  int UPDATE_UP = 1;
private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what){
            case UPDATE_UP:
                info.setText(msg.obj.toString());
                break;
        }
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    input = findViewById(R.id.input);
    button=  findViewById(R.id.query);
    info = findViewById(R.id.info);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Thread(
                    new Runnable() {
                        @Override
                        public void run() {
                            input.getText().toString();
                        }
                    }
            ).start();
        }
    });
}
private String StrUrl = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm";

private void SelectNum(String Num){
    //创建HpptClent
    HttpClient client = HttpClients.createDefault();
    //HpptClient
    HttpGet get = new HttpGet(StrUrl + "?tel=" + Num);
    //执行请求
    try {
        HttpResponse response = client.execute(get);
        //得到状态码
        int statusCode = response.getStatusLine().getStatusCode();

        if(statusCode == 200){

            String result = EntityUtils.toString(response.getEntity());
            handler.sendMessage(handler.obtainMessage(UPDATE_UP,result));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

你可以使用 Apache HttpComponents 中的 HttpClient 来进行 https 请求,并使用连接池来提高性能。下面是一个示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; import javax.net.ssl.SSLContext; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; public class HttpsClientUtil { private static final int MAX_TOTAL_CONNECTIONS = 200; private static final int MAX_PER_ROUTE_CONNECTIONS = 20; private static final int CONNECTION_TIMEOUT_MS = 5000; private static final int SOCKET_TIMEOUT_MS = 10000; private static CloseableHttpClient httpClient; static { try { SSLContext sslContext = SSLContexts.custom().build(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", socketFactory) .build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS); connectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE_CONNECTIONS); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(CONNECTION_TIMEOUT_MS) .setSocketTimeout(SOCKET_TIMEOUT_MS) .build(); httpClient = HttpClientBuilder.create() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .build(); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { throw new RuntimeException(e); } } public static String post(String url, List<BasicNameValuePair> parameters) throws IOException { HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(parameters, StandardCharsets.UTF_8)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity, StandardCharsets.UTF_8); } } ``` 使用方法: ```java List<BasicNameValuePair> parameters = new ArrayList<>(); parameters.add(new BasicNameValuePair("key1", "value1")); parameters.add(new BasicNameValuePair("key2", "value2")); String response = HttpsClientUtil.post("https://example.com/api", parameters); ``` 此处仅提供一个简单的示例,实际使用时需要根据具体情况进行调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值