Java post请求工具类

1.post请求 参数为?a=1&b=2&c=3
2.post请求 参数为{“a”:1,“b”:2,“c”:3} JSON格式


package cn.test.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import com.alibaba.fastjson.JSONObject;

public class URLConnection {
	 
	/**
	 * post请求封装 参数为?a=1&b=2&c=3
	 * @param path 接口地址
	 * @param Info 参数
	 * @return
	 * @throws IOException
	 */
    public static JSONObject postResponse(String path,String Info) throws IOException{
         
        //1, 得到URL对象 
        URL url = new URL(path); 
           
        //2, 打开连接 
        HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
           
        //3, 设置提交类型 
        conn.setRequestMethod("POST"); 
           
        //4, 设置允许写出数据,默认是不允许 false 
        conn.setDoOutput(true); 
        conn.setDoInput(true);//当前的连接可以从服务器读取内容, 默认是true 
           
        //5, 获取向服务器写出数据的流 
        OutputStream os = conn.getOutputStream(); 
        //参数是键值队  , 不以"?"开始 
        os.write(Info.getBytes()); 
        //os.write("googleTokenKey=&username=admin&password=5df5c29ae86331e1b5b526ad90d767e4".getBytes()); 
        os.flush();
        //6, 获取响应的数据 
       //得到服务器写回的响应数据 
        BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
        String str = br.readLine();   
        JSONObject json = JSONObject.parseObject(str);
        
        System.out.println("响应内容为:  " + json); 
               
      return  json;
    }
    /**
	 * post请求封装 参数为{"a":1,"b":2,"c":3}
	 * @param path 接口地址
	 * @param Info 参数
	 * @return
	 * @throws IOException
	 */
    public static JSONObject postResponse(String path,JSONObject Info) throws IOException{
    	HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(path);
        
        post.setHeader("Content-Type", "application/json");
        post.addHeader("Authorization", "Basic YWRtaW46");
        String result = "";
        
        try {
            StringEntity s = new StringEntity(Info.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
            post.setEntity(s);

            // 发送请求
            HttpResponse httpResponse = client.execute(post);

            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            strber.append(line + "\n");
            inStream.close();

            result = strber.toString();
            System.out.println(result);
            
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("请求服务器成功,做相应处理");
            } else {
                System.out.println("请求服务端失败");
            }

        } catch (Exception e) {
            System.out.println("请求异常");
            throw new RuntimeException(e);
        }

        return JSONObject.parseObject(result);
    }
	
}
//main
public static void main(String[] args) {
	try {
		JSONObject json = new JSONObject();
		
		//第一种post请求 参数为 a=1&b=2&c=3
		json = URLConnection.postResponse("https://www.apiopen.top/weatherApi", "city=上海&&test=111");
		System.out.println("json的数据为:" + json);
		
		//第二种post请求 参数为 json
		json.put("test", "参数1");
		json.put("test2", "参数2");
		json = URLConnection.postResponse("http://url", json);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Java中有多种HTTP请求工具类可供使用,其中一种是http-request。它基于URLConnection实现,不依赖于HttpClient。使用http-request发送GET请求示例如下: 1. 引入依赖: ``` <dependency> <groupId>com.github.kevinsawicki</groupId> <artifactId>http-request</artifactId> <version>5.6</version> </dependency> ``` 2. 发送GET请求获取响应报文: ```java String response = HttpRequest.get("http://www.baidu.com").body(); System.out.println("Response was: " + response); ``` 3. 发送GET请求获取响应码: ```java int code = HttpRequest.get("http://google.com").code(); ``` 除了http-request,还有其他一些常用的HTTP请求工具类,比如HttpUtil。使用HttpUtil发送GET请求的示例代码如下: ```java // 最简单的HTTP请求,自动判断编码 String result1 = HttpUtil.get("https://www.baidu.com"); // 自定义请求页面的编码 String result2 = HttpUtil.get("https://www.baidu.com", CharsetUtil.CHARSET_UTF_8); // 传入http参数,参数会自动做URL编码,拼接在URL中 HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("city", "北京"); String result3 = HttpUtil.get("https://www.baidu.com", paramMap); ``` 如果需要发送POST请求,可以使用HttpUtil的post方法,示例代码如下: ```java HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("city", "北京"); String result = HttpUtil.post("https://www.baidu.com", paramMap); ``` 另外,如果需要文件上传,可以将参数中的键指定为"file",值设为文件对象即可,示例代码如下: ```java HashMap<String, Object> paramMap = new HashMap<>();paramMap.put("file", FileUtil.file("D:\\face.jpg")); String result = HttpUtil.post("https://www.baidu.com", paramMap); ``` 以上是一些常用的Java HTTP请求工具类,你可以根据具体需求选择适合的工具类来发送HTTP请求。请问您还有其他相关问题吗? 相关问题: 1. Java中还有哪些常用的HTTP请求工具类? 2. 如何处理HTTP请求的返回结果? 3. 如何设置HTTP请求的超时时间?

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值