JAVA sends http get and post request and calls http interface
- 2021-07-24 11:04:38
- OfStack
3 Examples-JAVA sends http get/post request, calls http interface, method
Example 1: Using HttpClient (commons-httpclient-3. 0. jar
Download address of jar: http://xiazai.ofstack.com/201904/yuanma/commons-httpclient-3. 0. rar
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
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 HttpTool {
/**
* Send post Request
*
* @author Michael -----CSDN: http://blog.csdn.net/capmiachael
* @param params
* Parameter
* @param requestUrl
* Request address
* @param authorization
* Power of Attorney
* @return Return results
* @throws IOException
*/
public static String sendPost(String params, String requestUrl,
String authorization) throws IOException {
byte[] requestBytes = params.getBytes("utf-8"); // Convert the parameter to 2 Binary flow
HttpClient httpClient = new HttpClient();// Client instantiation
PostMethod postMethod = new PostMethod(requestUrl);
// Set the request header Authorization
postMethod.setRequestHeader("Authorization", "Basic " + authorization);
// Set the request header Content-Type
postMethod.setRequestHeader("Content-Type", "application/json");
InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
requestBytes.length);
RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
requestBytes.length, "application/json; charset=utf-8"); // Request body
postMethod.setRequestEntity(requestEntity);
httpClient.executeMethod(postMethod);// Execute request
InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// Gets the returned stream
byte[] datas = null;
try {
datas = readInputStream(soapResponseStream);// Read data from the input stream
} catch (Exception e) {
e.printStackTrace();
}
String result = new String(datas, "UTF-8");// Will 2 Binary flow to String
// Print return results
// System.out.println(result);
return result;
}
/**
* Read data from the input stream
*
* @param inStream
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inStream.close();
return data;
}
}
Example 2:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
/**
* Http Request tool class
* @author snowfigure
* @since 2014-8-24 13:30:56
* @version v1.0.1
*/
public class HttpRequestUtil {
static boolean proxySet = false;
static String proxyHost = "127.0.0.1";
static int proxyPort = 8087;
/**
* Code
* @param source
* @return
*/
public static String urlEncode(String source,String encode) {
String result = source;
try {
result = java.net.URLEncoder.encode(source,encode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "0";
}
return result;
}
public static String urlEncodeGBK(String source) {
String result = source;
try {
result = java.net.URLEncoder.encode(source,"GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "0";
}
return result;
}
/**
* Initiate http Request to get the return result
* @param req_url Request address
* @return
*/
public static String httpRequest(String req_url) {
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(req_url);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(false);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
// Converts the returned input stream to a string
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// Release resources
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
} catch (Exception e) {
System.out.println(e.getStackTrace());
}
return buffer.toString();
}
/**
* Send http Request to get the returned input stream
* @param requestUrl Request address
* @return InputStream
*/
public static InputStream httpRequestIO(String requestUrl) {
InputStream inputStream = null;
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoInput(true);
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
// Get the returned input stream
inputStream = httpUrlConn.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
return inputStream;
}
/**
* To the specified URL Send GET Request for the method
*
* @param url
* Sending the requested URL
* @param param
* Request parameter, which should be name1=value1&name2=value2 The form of.
* @return URL The response result of the remote resource represented by
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// Open and URL Connection between
URLConnection connection = realUrl.openConnection();
// Setting Common Request Properties
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// Establish an actual connection
connection.connect();
// Get all response header fields
Map<String, List<String>> map = connection.getHeaderFields();
// Traverse all response header fields
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// Definition BufferedReader Input stream to read URL Response of
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println(" Send GET Exception in request! " + e);
e.printStackTrace();
}
// Use finally Block to close the input stream
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* To the specified URL Send POST Request for the method
*
* @param url
* Sending the requested URL
* @param param
* Request parameter, which should be name1=value1&name2=value2 The form of.
* @param isproxy
* Whether to use proxy mode
* @return The response result of the remote resource represented by
*/
public static String sendPost(String url, String param,boolean isproxy) {
OutputStreamWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
HttpURLConnection conn = null;
if(isproxy){// Use proxy mode
@SuppressWarnings("static-access")
Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyHost, proxyPort));
conn = (HttpURLConnection) realUrl.openConnection(proxy);
}else{
conn = (HttpURLConnection) realUrl.openConnection();
}
// Open and URL Connection between
// Send POST The request must be set with the following two lines
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST"); // POST Method
// Setting Common Request Properties
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.connect();
// Get URLConnection The output stream corresponding to the object
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// Send request parameters
out.write(param);
// flush Buffering of output stream
out.flush();
// Definition BufferedReader Input stream to read URL Response of
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println(" Send POST Exception in request! "+e);
e.printStackTrace();
}
// Use finally Block to close the output stream, the input stream
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
//demo: Proxy access
String url = "http://api.adf.ly/api.php";
String para = "key=youkeyid&youuid=uid&advert_type=int&domain=adf.ly&url=http://somewebsite.com";
String sr=HttpRequestUtil.sendPost(url,para,true);
System.out.println(sr);
}
}
Example 3
/**
* Send Http post Request
*
* @param xmlInfo
* json Converted to a string
* @param URL
* Request url
* @return Return information
*/
public static String doHttpPost(String xmlInfo, String URL) {
System.out.println(" Initiated data :" + xmlInfo);
byte[] xmlData = xmlInfo.getBytes();
InputStream instr = null;
java.io.ByteArrayOutputStream out = null;
try {
URL url = new URL(URL);
URLConnection urlCon = url.openConnection();
urlCon.setDoOutput(true);
urlCon.setDoInput(true);
urlCon.setUseCaches(false);
urlCon.setRequestProperty("content-Type", "application/json");
urlCon.setRequestProperty("charset", "utf-8");
urlCon.setRequestProperty("Content-length",
String.valueOf(xmlData.length));
System.out.println(String.valueOf(xmlData.length));
DataOutputStream printout = new DataOutputStream(
urlCon.getOutputStream());
printout.write(xmlData);
printout.flush();
printout.close();
instr = urlCon.getInputStream();
byte[] bis = IOUtils.toByteArray(instr);
String ResponseString = new String(bis, "UTF-8");
if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
System.out.println(" Returns null ");
}
System.out.println(" The returned data is :" + ResponseString);
return ResponseString;
} catch (Exception e) {
e.printStackTrace();
return "0";
} finally {
try {
out.close();
instr.close();
} catch (Exception ex) {
return "0";
}
}
}