java web 几种 http请求接口处理方式(消息头加入参数)

1、

package com.lt.deviceapi.utils;

import org.apache.http.HttpEntity;
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.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

public class HttpClientUtils {


    public String httpClientSend(String allConfigUrl) {
        BufferedReader in = null;
        StringBuffer result;
        try {
            URI uri = new URI(allConfigUrl);
            URL url = uri.toURL();
            URLConnection connection = url.openConnection();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "utf-8");
            connection.connect();
            result = new StringBuffer();
            //读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }

            return result.toString();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }
}

2、RestTemplate 方式


import org.apache.commons.httpclient.HttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import net.sf.json.JSONObject;



           RestTemplate restTemplate = new RestTemplate();
			HttpHeaders headers = new HttpHeaders();
			MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
			headers.setContentType(type);
			headers.add("Action",headerType);//header  中加入参数
			JSONObject jsonObj = JSONObject.fromObject(map);//传入参数 Map<String,Object>
			HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
			ResponseEntity<String> exchange = restTemplate.exchange(sendUrl,
					HttpMethod.POST, formEntity, String.class);
			JSONArray jsonArraye=JSONArray.fromObject(exchange.getBody());

后期和.net进行http接口访问时,发现对方接受参数都为空

将map替换
 LinkedMultiValueMap<String,Object> body=new LinkedMultiValueMap<String,Object>();
body.add("username", userName);//key相同,值会拼接
//不转json
HttpEntity formEntity = new HttpEntity(body, headers);
发送
ResponseEntity<String> exchange = restTemplate.exchange(sendUrl,
					HttpMethod.POST, formEntity, String.class);

3、HttpURLConnection 方式

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

	URL url = new URL(sendUrl);
	            //打开和url之间的连接
	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	            PrintWriter out = null;
	            //请求方式
	          conn.setRequestMethod("POST");
//	           //设置通用的请求属性
	          conn.setRequestProperty("Action",headerType); //header  加入参数
	            //设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
	            //最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
	            //post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
	            conn.setDoOutput(true);
	            conn.setDoInput(true);
	            //获取URLConnection对象对应的输出流
	            out = new PrintWriter(conn.getOutputStream());
	            //发送请求参数即数据
	            Gson gson=new Gson();
	            //传入的参数
	            String param=gson.toJson(map);   //参数
	            out.print(param);
	            //缓冲数据
	            out.flush();
	            //获取URLConnection对象对应的输入流
	            InputStream is = conn.getInputStream();
	            //构造一个字符流缓存
	            BufferedReader br = new BufferedReader(new InputStreamReader(is));
	            String str = "";
	            while ((str = br.readLine()) != null) {
	                System.out.println(str);
	            }
	            //关闭流
	            is.close();
	            //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
	            //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
	            conn.disconnect();
	            System.out.println("完整结束");

4、HttpClient 方式

import org.apache.http.HttpEntity;
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.HttpClients;
import org.apache.http.util.EntityUtils;


HttpClient httpClient = null;
HttpPost postMethod = null;
HttpResponse response = null;


			httpClient = HttpClients.createDefault();
			postMethod = new HttpPost(sendUrl);//传入URL地址
            //设置请求头
			postMethod.addHeader("Content-type", "application/json; charset=utf-8");
			postMethod.addHeader("Action",headerType);//设置请求头
            //传入请求参数
			String params = JSON.toJSONString(map);
			
			postMethod.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
			
			response = httpClient.execute(postMethod);//获取响应
			
			int statusCode = response.getStatusLine().getStatusCode();
		
			System.out.println("HTTP Status Code:" + statusCode);
		
			if (statusCode != HttpStatus.SC_OK) {
				System.out.println("HTTP请求未成功!HTTP Status Code:" + response.getStatusLine());
			}
			HttpEntity httpEntity = response.getEntity();
			
			String reponseContent = EntityUtils.toString(httpEntity);
			EntityUtils.consume(httpEntity);//释放资源
			System.out.println("响应内容:" + reponseContent);

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值