java http HttpClient get post json和form格式body 简单使用示例

最新maven依赖

		<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
		<dependency>
		    <groupId>org.apache.httpcomponents</groupId>
		    <artifactId>httpclient</artifactId>
		    <version>4.5.13</version>
		</dependency>

        <!-- json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>

HttpGet 示例:

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;

public class Test1 {
	public static void main(String[] args) {
    		try {
                CloseableHttpClient client = HttpClients.createDefault();    //创建一个http客户端
                HttpGet httpGet = new HttpGet(StringTool.urlEncode("http://127.0.0.1:8081/test?id=123456")); // 通过httpget方式来实现我们的get请求
                RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(1000)
                    .setSocketTimeout(1000) // 服务端相应超时
                    .setConnectTimeout(2000) // 建立socket链接超时时间
                    .build();
            	httpGet.setConfig(requestConfig);
                CloseableHttpResponse Response = client.execute(httpGet); // 通过client调用execute方法,得到我们的执行结果就是一个response,所有的数据都封装在response里面了
                System.out.println(Response.getProtocolVersion());
                System.out.println(Response.getStatusLine());  //打印捕获的返回状态
                System.out.println("status="+Response.getStatusLine().getStatusCode());    //打印捕获的状态码
                String bodyAsString = EntityUtils.toString(Response.getEntity(),"UTF-8");
                System.out.println("响应内容:" + bodyAsString);
                Response.close();  // 关闭
            }catch (Exception e){
                
            }
    }
            
	public static String urlEncode(String url) throws UnsupportedEncodingException {
        if(url == null) {
            return null;
        }

        final String reserved_char = ";/?:@=&";
        String ret = "";
        for(int i=0; i < url.length(); i++) {
            String cs = String.valueOf( url.charAt(i) );
            if(reserved_char.contains(cs)){
                ret += cs;
            }else{
                ret += URLEncoder.encode(cs, "utf-8");
            }
        }
        return ret.replace("+", "%20");
    }
}

HttpPost json格式body示例:

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class Test2 {
    public static void main(String[] args) {
        try {
            CloseableHttpClient client = HttpClients.createDefault();    //创建一个http客户端
            HttpPost httpPost = new HttpPost("http://127.0.0.1:8881/test");
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(1000)
                    .setSocketTimeout(1000) // 服务端相应超时
                    .setConnectTimeout(2000) // 建立socket链接超时时间
                    .build();
            httpPost.setConfig(requestConfig);
            //head
            httpPost.addHeader("Content-Type","application/json");
            //body
            JSONObject params = new JSONObject();
            params.put("test1","1234");
            params.put("test2","abc");
            String requestParams = params.toString();
            StringEntity postingString = new StringEntity(requestParams, "utf-8");
            httpPost.setEntity(postingString);

            CloseableHttpResponse Response = client.execute(httpPost); // 通过client调用execute方法,得到我们的执行结果就是一个response,所有的数据都封装在response里面了
            System.out.println(Response.getProtocolVersion());
            System.out.println(Response.getStatusLine());  //打印捕获的返回状态
            System.out.println("status="+Response.getStatusLine().getStatusCode());    //打印捕获的状态码
            String bodyAsString = EntityUtils.toString(Response.getEntity(),"UTF-8");
            System.out.println("resp body:" + bodyAsString);
            Response.close();  // 关闭
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

HttpPost form格式body示例:

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class Test3 {
    public static void main(String[] args) {
        try {
            CloseableHttpClient client = HttpClients.createDefault();    //创建一个http客户端
            HttpPost httpPost = new HttpPost("http://127.0.0.1:8881/test"); 
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(1000)
                    .setSocketTimeout(1000) // 服务端相应超时
                    .setConnectTimeout(2000) // 建立socket链接超时时间
                    .build();
            httpPost.setConfig(requestConfig);
            //head
            httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
            //form 格式 body
            List<NameValuePair> parameters = new ArrayList<>();
            parameters.add(new BasicNameValuePair("test1","1234"));
            parameters.add(new BasicNameValuePair("test2","abc"));
            HttpEntity entity = new UrlEncodedFormEntity(parameters,"utf-8");
            httpPost.setEntity(entity);

            CloseableHttpResponse Response = client.execute(httpPost); // 通过client调用execute方法,得到我们的执行结果就是一个response,所有的数据都封装在response里面了
            System.out.println(Response.getProtocolVersion());
            System.out.println(Response.getStatusLine());  //打印捕获的返回状态
            System.out.println("status="+Response.getStatusLine().getStatusCode());    //打印捕获的状态码
            String bodyAsString = EntityUtils.toString(Response.getEntity(),"UTF-8");
            System.out.println("resp body:" + bodyAsString);
            Response.close();  // 关闭
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您也可以使用Apache HttpClient库来模拟发送POST请求,并将JSON数据作为请求体发送。以下是一个示例代码: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import java.io.BufferedReader; import java.io.InputStreamReader; public class PostJsonRequest { public static void main(String[] args) { try { // 设置请求URL和JSON数据 String url = "http://example.com/api"; String json = "{\"name\": \"John\", \"age\": 30}"; // 创建HttpClientHttpPost对象 HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); // 将JSON数据作为请求体发送 StringEntity entity = new StringEntity(json); post.setEntity(entity); post.setHeader("Content-type", "application/json"); post.setHeader("Accept", "application/json"); // 发送请求并获取响应 HttpResponse response = client.execute(post); // 打印响应内容 BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } } } ``` 在上述示例中,我们使用了Apache HttpClient库来创建HttpClientHttpPost对象,并将JSON数据作为请求体发送。注意:在实际使用时,您需要将URL和JSON数据替换为实际的值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值