POST and GET requests in java

Java's get and post method requests:

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 {

 

    /**

     * Send a POST request to the specified URL

     * 

     * @param url

     * The URL to send the request to

     * @param param

     *            

     * The response result of the remote resource represented by @return

     */

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

 

String body = "";  

//Create httpclient object  

CloseableHttpClient client = HttpClients.createDefault();  

//Create post method request object  

HttpPost httpPost = new HttpPost(url);  

 

//load parameters  

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

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

//Set parameters to the request object  

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

 

//Set header information  

//Specify the 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)");  

 

//Execute the request operation and get the result (synchronous blocking)  

CloseableHttpResponse response = client.execute(httpPost);  

// get the result entity  

HttpEntity entity = response.getEntity();  

if (entity != null) {  

// Convert the result entity to String type according to the specified encoding  

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

}  

EntityUtils.consume(entity);  

// release the link  

response.close();  

return body; 

   

    }   

 

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

        // The url of the Post request, unlike get, does not require parameters

        URL postUrl = new URL(url);

        // open the connection

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

        // Set whether to output to the connection, because this is a post request, the parameters should be placed in

        // In the http body, so it needs to be set to true

        connection.setDoOutput(true);

        // Read from the connection. Default is true.

        connection.setDoInput(true);

        // Default is GET method

        connection.setRequestMethod("POST");

        // set character encoding

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

        // Post request cannot use cache

        connection.setUseCaches(false);      

        connection.setInstanceFollowRedirects(true);

        // Configure the Content-type of this connection, set to application/x-www-form-urlencoded

        // Means that the body is a urlencoded encoded form parameter, below we can see that we use URLEncoder.encode for the body content

        // do the encoding

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

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

        // Connection, the configuration from postUrl.openConnection() must be completed before connect,

        // Note that connection.getOutputStream will implicitly connect.

        connection.connect();

        DataOutputStream out = new DataOutputStream(connection

                .getOutputStream());

        // The URL-encoded contend

        // Body, the content of the body is actually the same as the parameter string after '?' in the URL of get

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

        // DataOutputStream.writeBytes writes the 16-bit unicode characters in the string to the stream as 8-bit characters

        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;

 

    }

}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326840348&siteId=291194637