Several recently summarized in a few handling problems Use Code demo

demo1: http request several different ways Summary:

-------------------------------------------------------------------------------------------------

Post a new version of the request method:

 Based version:

        <!--&lt;!&ndash; https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient &ndash;&gt;-->
        <!--<dependency>-->
            <!--<groupId>org.apache.httpcomponents</groupId>-->
            <!--<artifactId>httpclient</artifactId>-->
            <!--<version>4.5.5</version>-->
        <!--</dependency>-->

 

//                String uploadResponse = Request.Post(nodeAddress + "/" + bucketName + "/" + objectName)
//                        .addHeader("x-nos-token", uploadToken)
//                        .bodyByteArray(chunkData, 0, readLen)
//                        .execute()
//                        .returnContent()
//                        .toString();

-------------------------------------------------------------------------------------------------

Post request version way:

//     public static String the doPost (URL String, String token, byte [] the chunk, OFF int, int len)
 //     {
 //         CloseableHttpClient httpClient = null;
 //         CloseableHttpResponse the httpResponse = null;
 //         String Result = "";
 / /         // Create instance httpClient
 @         httpClient HttpClients.createDefault = ();
 //         // Create instance HttpPost remote connection
 @         HttpPost HttpPost = new new HttpPost (URL);
 //         // configuration request parameter examples
 //         RequestConfig requestConfig = RequestConfig .custom (). setConnectTimeout (35000) // set the connection timeout hosting services
 //                .setConnectionRequestTimeout (35000) // set the connection request time
 //                 .setSocketTimeout (60000) // set the read data connection timeout
 //                 .build ();
 //         // setting to httpPost instance
 //         httpPost.setConfig ( requestConfig);
 //         // set the request header
 //         httpPost.addHeader ( "X-NOS-token", token);
 //         // package post request parameter
 //         // set the parameters for the encapsulated request HttpPost
 // the HttpEntity = new new ByteArrayEntity RequestEntity (the chunk, 0, len);
 //         httpPost.setEntity (RequestEntity);
 // 
//         the try {
//             // httpClient post requests on the object, the object parameters and returns a response
 //             the httpResponse = httpClient.execute (HttpPost);
 //             // get a response from the response object content
 //             the HttpEntity = httpResponse.getEntity Entity ();
 //             = EntityUtils.toString Result (Entity);
 //         } the catch (ClientProtocolException E) {
 //             e.printStackTrace ();
 //         } the catch (IOException E) {
 //             e.printStackTrace ();
 //         } the finally {
 //             // Close the resource
 //             IF (null! = httpResponse) {
 //                 the try {
//                    httpResponse.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            if (null != httpClient) {
//                try {
//                    httpClient.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return result;
//    }

-------------------------------------------------------------------------------------------------

Post request version way:

sendPost static String public (URL String, String token, byte [] the chunk, OFF int, int len) 
{
// create an object instance httpClient
HttpClient HttpClient httpClient new new = ();
// set timeout host servers httpClient: 15000 milliseconds
httpClient .getHttpConnectionManager () the getParams () setConnectionTimeout (15000);..
// Create instance object request method post
a PostMethod PostMethod a PostMethod new new = (URL);
// set the post request time
postMethod.getParams () setParameter (HttpMethodParams.SO_TIMEOUT,. 60000);
postMethod.addRequestHeader ( "X-NOS-token", token);
the try {
// JSON format parameter parsing

RequestEntity = new new ByteArrayRequestEntity Entity (the chunk);
postMethod.setRequestEntity (Entity);

httpClient.executeMethod(postMethod);
String result = postMethod.getResponseBodyAsString();
postMethod.releaseConnection();
return result;
} catch (IOException e) {
logger.info("POST请求发出失败!!!");
e.printStackTrace();
}
return null;
}

-------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------

A GET request method:

the doGet static String public (the HTTPUrl String) 
{
the HttpURLConnection Connection = null;
the InputStream IS = null;
the BufferedReader br = null;
// returns the resulting string
String Result = null;

the try {
// create a remote connection object url
URL url = new URL ( the HTTPUrl);
// open a connection object via the remote connection url, turn into strong class httpURLConnection
connection = (the httpURLConnection) url.openConnection ();
// set the connection mode: GET
connection.setRequestMethod ( "the GET");
// set the connection the host server timeout time: 15000 milliseconds
connection.setConnectTimeout (15,000);
// set the read data to return the remote time: 60000 milliseconds
connection.setReadTimeout (60,000);
// send a request
connection.connect ();
// connected by connection, takes an input stream
IF (connection.getResponseCode () == 200 is) {
IS = connection.getInputStream ();
// input stream IS package, and to specify the character set
br = new BufferedReader (new new the InputStreamReader (IS, "UTF-. 8"));
// store data
the StringBuffer SBF the StringBuffer new new = ();
String TEMP = null;
the while (! (br.readLine TEMP = ()) = null) {
sbf.append (TEMP);
sbf.append ( "\ R & lt \ n-");
}
Result sbf.toString = ();
}
} the catch (a MalformedURLException E) {
logger.error ( "illegal address format exception ...");
e.printStackTrace ();
} the catch (IOException E) {
logger.error ( "IO streams in the Get Request abnormality");
e.printStackTrace ();
} the finally {
// Close the resource
IF (br = null!) {
the try {
br.close ();
} the catch (IOException E) {
e.printStackTrace ();
}
}

IF (! IS = null) {
the try {
is.close ();
} the catch (IOException E) {
e.printStackTrace () ;
}
}

connection.disconnect (); // Close remote connection
}

return Result;
}

-------------------------------------------------------------------------------------------------

Recording process issues:

When using get request, if the request parameters in the URL contains special characters, special characters need to be escaped:

Some characters have special meaning in a URL, the basic encoding rules are as follows: 
            a special meaning hexadecimal value of 
1 . + Represents a space (no spaces in the URL)% 20  
2 ./ separate directories and subdirectories% 2F 
 3 separate reality.? URL and the parameter% 3F 
 . 4 .%% specify special character 25  
. 5 . #% indicates bookmark 23 is  
. 6 . & separator between the parameters specified in the URL% 26 

 

Solution:

//对鉴权参数做AES加密处理
requestId = java.net.URLEncoder.encode( AESCryptUtils.encode(requestId) );
data = java.net.URLEncoder.encode( AESCryptUtils.encode(data) );
action = java.net.URLEncoder.encode( AESCryptUtils.encode(action) );

String URL = AUTH_URL + "?" + "data=" + data + "&requestId=" + requestId + "&action=" + action;

  

Guess you like

Origin www.cnblogs.com/gxyandwmm/p/11985056.html