精华内容
下载资源
问答
  • // 设置请求方式 connection.addRequestProperty("x-access-token",token); // connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式 connection.setRequestProperty("Content-...
    HttpPost:
    	httpPost.addHeader("x-access-token",token);
    
    public static String post(String strURL, String params, String token) {
            System.out.println(strURL);
            System.out.println(params);
            Map<String,Object> map = new HashMap<>();
            BufferedReader reader = null;
            try {
                URL url = new URL(strURL);// 创建连接
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
                connection.setRequestMethod("POST"); // 设置请求方式
                connection.addRequestProperty("x-access-token",token);
                // connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
                connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
                connection.connect();
                //一定要用BufferedReader 来接收响应, 使用字节来接收响应的方法是接收不到内容的
                OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
                out.append(params);
                out.flush();
                out.close();
                // 读取响应
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line;
                String res = "";
                while ((line = reader.readLine()) != null) {
                    res += line;
                }
                reader.close();
                return res;
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
            return "请求错误"; // 自定义错误信息
        }
    
    HttpURLConnection:
    	connection.addRequestProperty("x-access-token",token);
    
     public static String sendRequest(String url, Map<String,Object> map,String token) {
            String result = "";
            try {
                CloseableHttpClient client = null;
                CloseableHttpResponse response = null;
                // 创建一个提交数据的容器
                List<BasicNameValuePair> parames = new ArrayList<>();
                Set<String> keys = map.keySet();
                for(String key:keys){
                    System.out.println("key值:"+key+" value值:"+map.get(key));
                    parames.add(new BasicNameValuePair(key, (String) map.get(key)));
                }
                try {
    
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(parames, "UTF-8"));
                    httpPost.addHeader("x-access-token",token);
                    client = HttpClients.createDefault();
                    response = client.execute(httpPost);
                    HttpEntity entity = response.getEntity();
                    result = EntityUtils.toString(entity);
                    System.out.println(result);
                } finally {
                    if (response != null) {
                        response.close();
                    }
                    if (client != null) {
                        client.close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    
    展开全文
  • JAVA两种POST请求方式

    千次阅读 2019-08-27 09:17:56
    package ... import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; imp...
    package com.ssh.insure.utils;
    
    import java.io.BufferedReader;
    import java.io.ByteArrayInputStream;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.URL;
    import java.net.URLConnection;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.methods.RequestEntity;
    
    public class POSTUtil {
    	
    	/**
    	 * 传统的POST/GET 请求方式
    	 * @param toURL
    	 * @param data
    	 * @return
    	 * @throws Exception
    	 */
    	public static String requestServiceJson(String toURL, String data)
    			throws Exception {
    		StringBuffer bs = new StringBuffer();
    		URL sendUrl = new URL(toURL.trim());
    		URLConnection connection = sendUrl.openConnection();
    		connection.setConnectTimeout(30000);
    		connection.setReadTimeout(30000);
    		connection.setDoOutput(true);
    		connection.setRequestProperty("Content-Type","application/json;chert=UTF-8");
    		OutputStreamWriter out = new OutputStreamWriter(
    				connection.getOutputStream(), "UTF-8");
    		out.write(data);
    		out.flush();
    		out.close();
    		connection.connect();
    		InputStream is = connection.getInputStream();
    		BufferedReader buffer = new BufferedReader(new InputStreamReader(is,"UTF-8"));
    
    		String l = null;
    		while ((l = buffer.readLine()) != null) {
    			bs.append(l);
    		}
    		return bs.toString();
    	}
    	
    
    	/**
    	 * 遇到了java.io.IOException: Server returned HTTP response code: 500 for URL错误信息,网上找了很多,例如修改User-Agent等都没能解决,我感觉还是java 客户端的访问被拒绝了,
    	 * 最后使用了org.apache.commons.httpclient.HttpClient包,通信代码如下:
    	 * @param toURL url
    	 * @param data 报文
    	 * @return 响应信息
    	 * @throws Exception
    	 */
    	public static String TCRequestJsonS(String toURL, String data) throws Exception {
    		byte[] requestBytes;
    		String soapRequestInfo = data;
    		requestBytes = soapRequestInfo.getBytes("utf-8");
    		HttpClient httpClient = new HttpClient();
    		PostMethod postMethod = new PostMethod(toURL);
    		postMethod.setRequestHeader("SOAPAction", "http://tempuri.org/GetMiscInfo");//Soap Action Header!
    		InputStream inputStream = new ByteArrayInputStream(requestBytes, 0, requestBytes.length);
    		RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, requestBytes.length, "application/json; charset=utf-8");
    		postMethod.setRequestEntity(requestEntity);
    		int state = httpClient.executeMethod(postMethod);
    		InputStream soapResponseStream = postMethod.getResponseBodyAsStream();
    		InputStreamReader inputStreamReader = new InputStreamReader(soapResponseStream);
    		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    		String responseLine = "";
    		String soapResponseInfo = "";
    		while((responseLine = bufferedReader.readLine()) != null) {
    			soapResponseInfo = soapResponseInfo + responseLine;
    		}
    		return soapResponseInfo;
    	}
    }
    

     

    展开全文
  • java form-data请求方式 请求接口

    千次阅读 2020-11-24 15:57:47
    java form-data请求方式 请求接口 参数示例 MultiValueMap<String, String> map= new LinkedMultiValueMap<>(); map.add("apikey", kakao_api_push_api_key); map.add("userid",kakao_api_push_userId...

    java form-data请求方式 请求接口


    java访问/请求/调用外部接口通用方法

    参数示例
    MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
                    map.add("apikey", kakao_api_push_api_key);
                    map.add("userid",kakao_api_push_userId);
                    map.add("token",token);
                    map.add("charset","utf-8");
    
    apiUrl  请求地址
    
    /**
         *  rest api 发送消息
         * @param apiUrl  请求地址
         * @param map
         * @return
         */
        public JSONObject httpConnect_send(String apiUrl,MultiValueMap<String, String> map) {
            JSONObject jsonObject = new JSONObject();
            log.info("【 api  send】参数:apiUrl={},map={}", apiUrl, map);
            try {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                List<MediaType> acceptableMediaTypes = new ArrayList<>();
                acceptableMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
                acceptableMediaTypes.add(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
                HttpEntity<MultiValueMap<String, String>> requestParams = new HttpEntity<>(map, headers);
                ResponseEntity<String> response = new RestTemplate().postForEntity(apiUrl, requestParams, String.class);
                String result = response.getBody();
                log.info("【 api kakao send】结果result={}",result);
                jsonObject = JSONObject.parseObject(result);
                jsonObject.put("responseCode","200");
            }catch (Exception e){
                log.error("【 api kakao send】异常",e);
                jsonObject.put("responseCode","500");
            }
            return jsonObject;
        }
    
    展开全文
  • java实现HTTP请求的四种方式

    万次阅读 多人点赞 2018-10-24 12:11:01
    目前JAVA实现HTTP请求的方法用的最多的有两种: 1、通过HTTPClient这种第三方的开源框架去实现。HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,HttpClient3.1 是 org.apache.commons....

    目前JAVA实现HTTP请求的方法用的最多的有两种:
    1、通过HTTPClient这种第三方的开源框架去实现。HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,HttpClient3.1 是 org.apache.commons.httpclient下操作远程 url的工具包,虽然已不再更新,但实现工作中使用httpClient3.1的代码还是很多,HttpClient4.5是org.apache.http.client下操作远程 url的工具包,最新的;
    2、通过HttpURLConnection去实现,HttpURLConnection是JAVA的标准类,是JAVA比较原生的一种实现方式。

    实现过程:

    GET:
    1、创建远程连接
    2、设置连接方式(get、post、put。。。)
    3、设置连接超时时间
    4、设置响应读取时间
    5、发起请求
    6、获取请求数据
    7、关闭连接
    
    POST:
    1、创建远程连接
    2、设置连接方式(get、post、put。。。)
    3、设置连接超时时间
    4、设置响应读取时间
    5、当向远程服务器传送数据/写数据时,需要设置为true(setDoOutput)
    6、当前向远程服务读取数据时,设置为true,该参数可有可无(setDoInput)
    7、设置传入参数的格式:(setRequestProperty)
    8、设置鉴权信息:Authorization:(setRequestProperty)
    9、设置参数
    10、发起请求
    11、获取请求数据
    12、关闭连接
    

    Java原生HttpURLConnection

    package com.ming.http;
    
    import org.springframework.lang.Nullable;
    
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * 文件名:  ${file_name}
     * 版权:    Copyright by ljm
     * 描述:
     * 修改人:  HuamingChen
     * 修改时间:2018/10/24
     * 跟踪单号:
     * 修改单号:
     * 修改内容:
     */
    public class HttpURLConnectionUtil {
        /**
         * http get请求
         * @param httpUrl 链接
         * @return 响应数据
         */
        public static String doGet(String httpUrl){
            //链接
            HttpURLConnection connection=null;
            InputStream is=null;
            BufferedReader br = null;
            StringBuffer result=new StringBuffer();
            try {
                //创建连接
                URL url=new URL(httpUrl);
                connection= (HttpURLConnection) url.openConnection();
                //设置请求方式
                connection.setRequestMethod("GET");
                //设置连接超时时间
                connection.setConnectTimeout(15000);
                //设置读取超时时间
                connection.setReadTimeout(15000);
                //开始连接
                connection.connect();
                //获取响应数据
                if(connection.getResponseCode()==200){
                    //获取返回的数据
                    is=connection.getInputStream();
                    if(is!=null){
                        br=new BufferedReader(new InputStreamReader(is,"UTF-8"));
                        String temp = null;
                        while ((temp=br.readLine())!=null){
                            result.append(temp);
                        }
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(br!=null){
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(is!=null){
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                connection.disconnect();// 关闭远程连接
            }
            return result.toString();
        }
    
        /**
         * post请求
         * @param httpUrl 链接
         * @param param 参数
         * @return
         */
        public static String doPost(String httpUrl, @Nullable String param) {
            StringBuffer result=new StringBuffer();
            //连接
            HttpURLConnection connection=null;
            OutputStream os=null;
            InputStream is=null;
            BufferedReader br=null;
            try {
                //创建连接对象
                URL url=new URL(httpUrl);
                //创建连接
                connection= (HttpURLConnection) url.openConnection();
                //设置请求方法
                connection.setRequestMethod("POST");
                //设置连接超时时间
                connection.setConnectTimeout(15000);
                //设置读取超时时间
                connection.setReadTimeout(15000);
                //设置是否可读取
                connection.setDoOutput(true);
                //设置响应是否可读取
                connection.setDoInput(true);
                //设置参数类型
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                //拼装参数
                if(param!=null&&!param.equals("")){
                    //设置参数
                    os=connection.getOutputStream();
                    //拼装参数
                    os.write(param.getBytes("UTF-8"));
                }
                //设置权限
                //设置请求头等
                //开启连接
                //connection.connect();
                //读取响应
                if(connection.getResponseCode()==200){
                    is=connection.getInputStream();
                    if(is!=null){
                        br=new BufferedReader(new InputStreamReader(is,"UTF-8"));
                        String temp=null;
                        if((temp=br.readLine())!=null){
                            result.append(temp);
                        }
                    }
                }
                //关闭连接
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(br!=null){
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(os!=null){
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(is!=null){
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //关闭连接
                connection.disconnect();
            }
            return result.toString();
        }
    
        public static void main(String[] str){
            /*String result=HttpURLConnectionUtil.doGet("http://localhost:8080/test");
            System.out.println(result);*/
            /*Map<String, Object> map=new HashMap<>();
            map.put("1","1");
            map.put("2","2");
            map.put("3","3");
            System.out.println(HttpURLConnectionUtil.getParamStr(map));*/
        }
    }
    

    Apache HttpClient3.1(common)

    package com.ming.http;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    
    import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    
    /**
     * 文件名:  ${file_name}
     * 版权:    Copyright by ljm
     * 描述:
     * 修改人:  HuamingChen
     * 修改时间:2018/10/24
     * 跟踪单号:
     * 修改单号:
     * 修改内容:
     */
    public class HttpClient3 {
        /**
         * get请求
         * @param url 链接
         * @return 响应参数
         */
        public static String doGet(String url) {
            // 输入流
            InputStream is = null;
            BufferedReader br = null;
            StringBuffer result=new StringBuffer();
            // 创建httpClient实例
            HttpClient httpClient=new HttpClient();
            // 设置http连接主机服务超时时间:15000毫秒
            // 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
            //创建请求方法
            GetMethod getMethod=new GetMethod(url);
            // 设置get请求超时为60000毫秒
            getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,60000);
            // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(3, true));
            //执行get方法
            try {
                int statusCode=httpClient.executeMethod(getMethod);
                // 判断返回码
                if (statusCode != HttpStatus.SC_OK) {
                    // 如果状态码返回的不是ok,说明失败了,打印错误信息
                    System.err.println("Method faild: " + getMethod.getStatusLine());
                } else {
                    // 通过getMethod实例,获取远程的一个输入流
                    is = getMethod.getResponseBodyAsStream();
                    // 包装输入流
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    
                    // 读取封装的输入流
                    String temp = null;
                    while ((temp = br.readLine()) != null) {
                        result.append(temp);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                // 关闭资源
                if (null != br) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 释放连接
                getMethod.releaseConnection();
            }
            return result.toString();
        }
    
        public static String doPost(String url, Map<String, Object> paramMap) {
            // 获取输入流
            InputStream is = null;
            BufferedReader br = null;
            String result = null;
            // 创建httpClient实例对象
            HttpClient httpClient = new HttpClient();
            // 设置httpClient连接主机服务器超时时间:15000毫秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
            // 创建post请求方法实例对象
            PostMethod postMethod = new PostMethod(url);
            // 设置post请求超时时间
            postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    
            NameValuePair[] nvp = null;
            // 判断参数map集合paramMap是否为空
            if (null != paramMap && paramMap.size() > 0) {// 不为空
                // 创建键值参数对象数组,大小为参数的个数
                nvp = new NameValuePair[paramMap.size()];
                // 循环遍历参数集合map
                Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
                // 获取迭代器
                Iterator<Entry<String, Object>> iterator = entrySet.iterator();
    
                int index = 0;
                while (iterator.hasNext()) {
                    Entry<String, Object> mapEntry = iterator.next();
                    // 从mapEntry中获取key和value创建键值对象存放到数组中
                    try {
                        nvp[index] = new NameValuePair(mapEntry.getKey(),
                                new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    index++;
                }
            }
            // 判断nvp数组是否为空
            if (null != nvp && nvp.length > 0) {
                // 将参数存放到requestBody对象中
                postMethod.setRequestBody(nvp);
            }
            // 执行POST方法
            try {
                int statusCode = httpClient.executeMethod(postMethod);
                // 判断是否成功
                if (statusCode != HttpStatus.SC_OK) {
                    System.err.println("Method faild: " + postMethod.getStatusLine());
                }
                // 获取远程返回的数据
                is = postMethod.getResponseBodyAsStream();
                // 封装输入流
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                }
    
                result = sbf.toString();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != br) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 释放连接
                postMethod.releaseConnection();
            }
            return result;
        }
    
        public static void main(String[] str){
           //System.out.println(HttpClient3.doGet("http://localhost:8080/test"));
            Map<String,Object> map=new HashMap<>();
            map.put("name","ming");
            System.out.println(HttpClient3.doPost("http://localhost:8080/testPost",map));
        }
    }
    

    Apache httpClient4.5

    package com.ming.http;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.*;
    import java.util.Map.Entry;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    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 HttpClient4 {
    
        public static String doGet(String url) {
            CloseableHttpClient httpClient = null;
            CloseableHttpResponse response = null;
            String result = "";
            try {
                // 通过址默认配置创建一个httpClient实例
                httpClient = HttpClients.createDefault();
                // 创建httpGet远程连接实例
                HttpGet httpGet = new HttpGet(url);
                // 设置请求头信息,鉴权
                httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
                // 设置配置请求参数
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
                        .setConnectionRequestTimeout(35000)// 请求超时时间
                        .setSocketTimeout(60000)// 数据读取超时时间
                        .build();
                // 为httpGet实例设置配置
                httpGet.setConfig(requestConfig);
                // 执行get请求得到返回对象
                response = httpClient.execute(httpGet);
                // 通过返回对象获取返回数据
                HttpEntity entity = response.getEntity();
                // 通过EntityUtils中的toString方法将结果转换为字符串
                result = EntityUtils.toString(entity);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != response) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != httpClient) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }
    
        public static String doPost(String url, Map<String, Object> paramMap) {
            CloseableHttpClient httpClient = null;
            CloseableHttpResponse httpResponse = null;
            String result = "";
            // 创建httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpPost远程连接实例
            HttpPost httpPost = new HttpPost(url);
            // 配置请求参数实例
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                    .setSocketTimeout(60000)// 设置读取数据连接超时时间
                    .build();
            // 为httpPost实例设置配置
            httpPost.setConfig(requestConfig);
            // 设置请求头
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            // 封装post请求参数
            if (null != paramMap && paramMap.size() > 0) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                // 通过map集成entrySet方法获取entity
                Set<Entry<String, Object>> entrySet = paramMap.entrySet();
                // 循环遍历,获取迭代器
                Iterator<Entry<String, Object>> iterator = entrySet.iterator();
                while (iterator.hasNext()) {
                    Entry<String, Object> mapEntry = iterator.next();
                    nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
                }
    
                // 为httpPost设置封装好的请求参数
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            try {
                // httpClient对象执行post请求,并返回响应参数对象
                httpResponse = httpClient.execute(httpPost);
                // 从响应对象中获取响应内容
                HttpEntity entity = httpResponse.getEntity();
                result = EntityUtils.toString(entity);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭资源
                if (null != httpResponse) {
                    try {
                        httpResponse.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != httpClient) {
                    try {
                        httpClient.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }
    
        public static void main(String str[]){
            System.out.println(HttpClient4.doGet("http://localhost:8080/test"));
            Map<String,Object> map=new HashMap<>();
            map.put("name","ming");
            System.out.println(HttpClient4.doPost("http://localhost:8080/testPost",map));
        }
    }
    

    Spring RestTemplate(比较建议使用这种方法)

    package com.ming.http;
    
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.MediaType;
    import org.springframework.web.client.RestTemplate;
    
    import javax.annotation.Resource;
    
    /**
     * 文件名:  ${file_name}
     * 版权:    Copyright by ljm
     * 描述:
     * 修改人:  HuamingChen
     * 修改时间:2018/10/24
     * 跟踪单号:
     * 修改单号:
     * 修改内容:
     */
    public class HttpTemplate {
    
        public static String httpGet(String url){
            RestTemplate restTemplate=new RestTemplate();
            String result=restTemplate.exchange(url, HttpMethod.GET,null,String.class).getBody();
            return result;
        }
    
        public static String httpPost(String url,String name){
            RestTemplate restTemplate=new RestTemplate();
            return restTemplate.postForEntity(url,name,String.class).getBody();
        }
    
        public static void main(String str[]){
            //System.out.println(HttpTemplate.httpGet("http://localhost:8080/test"));
            System.out.println(HttpTemplate.httpPost("http://localhost:8080/testPost1","ming"));
        }
    }
    

    Spring RestTemplate中几种常见的请求方式:
    https://blog.csdn.net/u012702547/article/details/77917939/

    展开全文
  • java发送https请求的例子

    热门讨论 2013-10-31 16:18:51
    java发送https请求的例子
  • java实现调用http请求的几种常见方式

    万次阅读 多人点赞 2019-05-25 02:23:36
    一、概述 在实际开发过程中,我们经常需要调用对方提供的...在Java项目中调用第三方接口的方式有: 1、通过JDK网络类Java.net.HttpURLConnection; 2、通过common封装好的HttpClient; 3、通过Apache封装好的Clos...
  • 使用java实现HTTP的GET请求

    千次阅读 2020-05-12 11:33:03
    在前几节我们详细讲解了http协议的相关信息,基于“知行合一”的原则,只有通过具体动手实践才有可能检验知识点被我们真正掌握,本节我们就使用代码实现http的get请求。 首先需要一个http服务器,基于简单原则,我...
  • java实现HTTP请求方式

    千次阅读 2018-10-24 09:44:40
    //设置请求方式 conn.setRequestMethod("POST"); //设置传入参数格式 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置鉴权信息:Authorization: Bearer da3efcbf...
  • JAVA发送HTTP请求方式总结

    万次阅读 多人点赞 2018-05-30 14:40:21
    java 发送HTTP请求方式总结 源代码:http://github.com/lovewenyo/HttpDemo 1. HttpURLConnection 使用JDK原生提供的net,无需其他jar包; HttpURLConnection是URLConnection的子类,提供更多的方法,...
  • java写post请求(添加post参数)

    千次阅读 2017-12-15 13:44:34
    [color=red]网址和参数需要...import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import j...
  • java发送xml格式HTTP请求

    千次阅读 2017-09-12 10:18:29
    import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamRead
  • server return http response code :405 for url 这个怎么解决,调用接口规定以put方式
  • java积累---HttpDelete请求方式传递参数

    万次阅读 2019-04-30 16:27:03
    然后就可以直接调用了,调用方式如下; HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url); // json 处理 httpdelete.setHeader("Content-Type", "application/json; charset=UTF-8");//or add...
  • JSON格式: JSONObject jsonObject = new JSONObject();  jsonObject.put("Action", "action");  jsonObject.put("UserId","11"...private static Stri
  • 发送Get请求,但是请求参数要放在请求body内,所以经过多方查证后整理出来以下代码。 2.POM依赖 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>...
  • Java实现Http/Https请求方式

    千次阅读 2018-04-17 16:57:14
    作为用Java为开发语言的后端开发,实现Http请求方式有原始Socket、URLConnection、HttpURLConnection、第三方工具HttpClient等。网络上已经有很多前人做了归纳,这里做个笔记: 1. java.ne...
  • 重点:java.net包下面有两个类是用来调用URL请求的。 第一个 URLconnection 只能使用常用的post方式请求 第二个 httpUrlconnection 可以主动设置四种请求方式 其中,这两个类都是可以设置header参数传参的...
  • java发送一个xml方式的http请求

    千次阅读 2019-07-19 11:05:33
    在项目中可以利用利用xml来...这里话如果是需要考虑到java效率的话这里可以使用Stringbuffer利用apeend来进行拼接 然后利用call类 进行一个传输 然后利用Document类 来获取XML里面的值: 然后在做处理就可以了。 ...
  • java解决请求跨域的两种方法

    万次阅读 2019-07-04 11:20:43
    java解决请求跨域问题,有以下两种写法 1.使用拦截器,实现javax.servlet.Filter接口 import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet....
  • * @param params 请求参数 * @return */ public String getWebServiceData(String url,String params) throws IOException { //接受返回报文 String result = new String(); URL u ...
  • Java实现拦截HTTP请求的几种方式

    万次阅读 2018-06-27 22:41:19
    Java的服务端开发当中,拦截器是很常见的业务场景,这里对Java开发当中几种常见的拦截器的实现方式进行记录和分析。案例说明基于Spring Boot环境。一:实现javax.servlet.Filter接口(使用过滤器方式拦截请求)...
  • JAVA发送POST请求

    万次阅读 2018-09-28 14:36:39
    java向第三方发送post请求,数据格式为json。废话不多说,直接上代码 import com.alibaba.fastjson.JSON; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods....
  • Java Post 请求 Map

    千次阅读 2017-12-22 17:54:26
    ①. SSLClient.javapackage ...import java.security.cert.CertificateException; import java.security.cert.X509Certificate;import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.n
  • 运用 Java 8 一个 HTTP 请求工具类

    千次阅读 2019-01-27 20:52:09
    三年多以前过一个 HTTP 请求类,然后又将其改进为链式风格的调用方式。虽然可以实现需求,基本上也没用重复的逻辑,但是编码上总是觉得怪怪的,当时也说不上哪里不对劲,尽管逻辑没错能实现,然而就是感觉谈不上...
  • Java raw 请求和获取

    万次阅读 2019-04-13 14:49:48
    raw方式使用的是纯字符串的数据上传方式;...java发送raw请求代码如下: public static JSONObject deviceRequest() { JSONObject result = null; try { String url = &quot;url 地址&quot;; ...
  • Java发送HTTP 请求

    万次阅读 2019-03-19 15:29:25
    请求http的Demo是个人亲测过,目前该方式已经在线上运行着。因为是http请求,所有发送post 和get 请求的demo都有在下方贴出,包括怎么测试,大家可直接 copy到自己的项目中使用。 正文 使用须知 为了避免大家引错...
  • import java.util.concurrent.Callable; @Slf4j @RestController public class AsyncCallableController { @Autowired private BusinessService businessService; @GetMapping(value = "/getData") public Callable...
  • java模拟Http Post请求带参数请求

    千次阅读 2021-03-05 11:49:50
    //启动执行请求,并获得返回值 CloseableHttpResponse response = client.execute(post); //得到返回的entity对象 HttpEntity entity = response.getEntity(); //把实体对象转换为string String result = ...
  • Java实现https请求

    千次阅读 2019-01-23 19:06:08
    // 设置请求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); /*如果是get请求,明文连接*/ if (HttpMethod.GET.toString().equalsIgnoreCase(requestMethod)) { httpUrlConn.connect(); } //...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,493,030
精华内容 597,212
关键字:

java怎么写请求方式

java 订阅