欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java的POST和GET请求

程序员文章站 2022-07-04 10:13:59
...

java的get和post方式请求:

package com.jfpay.util.http;

import java.io.BufferedReader;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLEncoder;

import java.util.ArrayList;

import java.util.List;

 

import org.apache.http.HttpEntity;

import org.apache.http.NameValuePair;

import org.apache.http.client.entity.UrlEncodedFormEntity;

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.springframework.expression.ParseException;

public class HttpRequest {

 

    /**

     * 向指定 URL 发送POST方法的请求

     * 

     * @param url

     *            发送请求的 URL

     * @param param

     *            

     * @return 所代表远程资源的响应结果

     */

    public static String readPost(String url, String xml) throws ParseException, IOException{

 

String body = "";  

//创建httpclient对象  

CloseableHttpClient client = HttpClients.createDefault();  

//创建post方式请求对象  

HttpPost httpPost = new HttpPost(url);  

 

//装填参数  

List<NameValuePair> nvps = new ArrayList<NameValuePair>();  

nvps.add(new BasicNameValuePair("xml", xml));  

//设置参数到请求对象中  

httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));  

 

//设置header信息  

//指定报文头【Content-type】、【User-Agent】  

httpPost.setHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");  

httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  

 

//执行请求操作,并拿到结果(同步阻塞)  

CloseableHttpResponse response = client.execute(httpPost);  

//获取结果实体  

HttpEntity entity = response.getEntity();  

if (entity != null) {  

//按指定编码转换结果实体为String类型  

body = EntityUtils.toString(entity, "utf-8");  

}  

EntityUtils.consume(entity);  

//释放链接  

response.close();  

return body; 

   

    }   

 

    public static String sendPost(String url,String xml) throws IOException {

        // Post请求的url,与get不同的是不需要带参数

        URL postUrl = new URL(url);

        // 打开连接

        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();     

        // 设置是否向connection输出,因为这个是post请求,参数要放在

        // http正文内,因此需要设为true

        connection.setDoOutput(true);

        // Read from the connection. Default is true.

        connection.setDoInput(true);

        // 默认是 GET方式

        connection.setRequestMethod("POST");

        // 设置字符编码

        connection.setRequestProperty("Accept-Charset", "utf-8");

        // Post 请求不能使用缓存

        connection.setUseCaches(false);      

        connection.setInstanceFollowRedirects(true);

        // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的

        // 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode

        // 进行编码

        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

        connection.setRequestProperty("contentType", "utf-8");

        // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,

        // 要注意的是connection.getOutputStream会隐含的进行connect。

        connection.connect();

        DataOutputStream out = new DataOutputStream(connection

                .getOutputStream());

        // The URL-encoded contend

        // 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致

        String content = "xml=" + URLEncoder.encode(xml, "utf-8");

        // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面

        out.writeBytes(content);

        out.flush();

        out.close(); 

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String line;

        String response = null;

        while ((line = reader.readLine()) != null){

        response=line;

        }

        reader.close();

        connection.disconnect();

return response;

 

    }

}

 

相关标签: java post get