1、無參請求
/**
* 無參數請求
* @param url
* @return
*/
public static String sendNoPara(String url){
try {
PostMethod postMethod = null;
postMethod = new PostMethod(url) ;
postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
//參數設置,需要注意的就是里邊不能傳NULL,要傳空字符串
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
int response = httpClient.executeMethod(postMethod); // 執行POST方法
String result = postMethod.getResponseBodyAsString() ;
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
2、有參數請求
/**
* 發送Post請求,請求參數格式為form;
* @return
*/
public static String sendByForm(String url, NameValuePair[] data){
try {
//String postURL = "https://aip.baidubce.com/rest/2.0/image-classify/v1/vehicle_damage";
PostMethod postMethod = null;
postMethod = new PostMethod(url) ;
postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
//參數設置,需要注意的就是里邊不能傳NULL,要傳空字符串
postMethod.setRequestBody(data);
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
int response = httpClient.executeMethod(postMethod); // 執行POST方法
InputStream in = postMethod.getResponseBodyAsStream();
//下面將stream轉換為String
StringBuffer sb = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in, "UTF-8");
char[] b = new char[4096];
for(int n; (n = isr.read(b)) != -1;) {
sb.append(new String(b, 0, n));
}
String returnStr = sb.toString();
return returnStr;
} catch (Exception e) {
// logger.info("請求異常"+e.getMessage(),e);
e.printStackTrace();
}
return null;
}
參數:
NameValuePair[] data = {
new NameValuePair("image",base64Str)
};
String result = RequestInterfaceUtil.sendByForm(url,data );