java調用post介面
1. java應用的post請求怎麼實現
在Java應用中實現POST請求,通常有兩種主流方法:通過URLConnection類和使用Apache HttpClient庫。
使用URLConnection類發送POST請求,是基於Java標准庫的功能。通過創建一個URL對象,然後通過其openConnection方法獲取一個URLConnection實例,最後利用這個實例的setRequestMethod方法設置請求方式為POST,並通過setEntity方法設置請求體。然後調用其connect方法發起請求,最後讀取響應信息。
而Apache HttpClient庫的使用,則提供了一種更高級、更靈活的方式實現POST請求。通過創建HttpClient實例,使用其創建Post方法生成HttpPost對象,設置請求頭如Content-Type等,再設置請求體,然後調用HttpClient實例的execute方法發起請求。最後讀取並處理響應結果。
在實際開發中,選擇哪種方法,主要取決於項目需求、團隊習慣和對代碼可維護性的考量。URLConnection適合輕量級應用,而Apache HttpClient適合對並發、非同步操作有較高要求的場景。
2. java中怎樣用post,get,put請求
java中用post,get,put請求方法:
public static String javaHttpGet(String url,String charSet){
String resultData = null;
try {
URL pathUrl = new URL(url); //創建一個URL對象
HttpURLConnection urlConnect = (HttpURLConnection) pathUrl.openConnection(); //打開一個HttpURLConnection連接
urlConnect.setConnectTimeout(30000); // 設置連接超時時間
urlConnect.connect();
if (urlConnect.getResponseCode() == 200) { //請求成功
resultData = readInputStream(urlConnect.getInputStream(), charSet);
}
} catch (MalformedURLException e) {
LogL.getInstance().getLog().error("URL出錯!", e);
} catch (IOException e) {
LogL.getInstance().getLog().error("讀取數據流出錯!", e);
}
return resultData;
}
public static String javaHttpPost(String url,Map<String,Object> map,String charSet){
String resultData=null;
StringBuffer params = new StringBuffer();
try {
Iterator<Entry<String, Object>> ir = map.entrySet().iterator();
while (ir.hasNext()) {
Map.Entry<String, Object> entry = (Map.Entry<String, Object>) ir.next();
params.append(URLEncoder.encode(entry.getKey(),charSet) + "=" + URLEncoder.encode(entry.getValue().toString(), charSet) + "&");
}
byte[] postData = params.deleteCharAt(params.length()).toString().getBytes();
URL pathUrl = new URL(url); //創建一個URL對象
HttpURLConnection urlConnect = (HttpURLConnection) pathUrl.openConnection();
urlConnect.setConnectTimeout(30000); // 設置連接超時時間
urlConnect.setDoOutput(true); //post請求必須設置允許輸出
urlConnect.setUseCaches(false); //post請求不能使用緩存
urlConnect.setRequestMethod("POST"); //設置post方式請求
urlConnect.setInstanceFollowRedirects(true);
urlConnect.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset="+charSet);// 配置請求Content-Type
urlConnect.connect(); // 開始連接
DataOutputStream dos = new DataOutputStream(urlConnect.getOutputStream()); // 發送請求參數
dos.write(postData);
dos.flush();
dos.close();
if (urlConnect.getResponseCode() == 200) { //請求成功
resultData = readInputStream(urlConnect.getInputStream(),charSet);
}
} catch (MalformedURLException e) {
LogL.getInstance().getLog().error("URL出錯!", e);
} catch (IOException e) {
LogL.getInstance().getLog().error("讀取數據流出錯!", e);
} catch (Exception e) {
LogL.getInstance().getLog().error("POST出錯!", e);
}
return resultData;
}
3. java語言使用post方式調用webService方式
WebService可以有Get、Post、Soap、Document四種方式調用,以下Java通過post方式調用WebService代碼:
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.io.OutputStreamWriter;
importjava.net.URL;
importjava.net.URLConnection;
importjava.net.URLEncoder;
importorg.apache.cxf.endpoint.Client;
importorg.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
/**
*功能描述:WebService調用
*
*/
publicclassClientTest{
/**
*功能描述:HTTP-POST
*
*/
publicStringpost(){
OutputStreamWriterout=null;
StringBuildersTotalString=newStringBuilder();
try{
URLurlTemp=newURL(
"http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity");
URLConnectionconnection=urlTemp.openConnection();
connection.setDoOutput(true);
out=newOutputStreamWriter(connection.getOutputStream(),"UTF-8");
StringBuffersb=newStringBuffer();
sb.append("byProvinceName=福建");
out.write(sb.toString());
out.flush();
StringsCurrentLine;
sCurrentLine="";
InputStreaml_urlStream;
l_urlStream=connection.getInputStream();//請求
BufferedReaderl_reader=newBufferedReader(newInputStreamReader(
l_urlStream));
while((sCurrentLine=l_reader.readLine())!=null){
sTotalString.append(sCurrentLine);
}
}catch(Exceptione){
e.printStackTrace();
}finally{
if(null!=out){
try{
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
returnsTotalString.toString();
}
}
4. java 介面調用,根據介面文檔寫測試,用post方法,剛怎麼做啊,有個完整的例子么
可使用android自帶的httpclient框架實現。
1. GET 方式傳遞參數
//先將參數放入List,再對參數進行URL編碼
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "數據")); //增加參數1
params.add(new BasicNameValuePair("param2", "value2"));//增加參數2
String param = URLEncodedUtils.format(params, "UTF-8");//對參數編碼
String baseUrl = "伺服器介面完整URL";
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);//將URL與參數拼接
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod); //發起GET請求
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//獲取伺服器響應內容
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
2. POST方式 方式傳遞參數
//和GET方式一樣,先將參數放入List
params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "Post方法"));//增加參數1
params.add(new BasicNameValuePair("param2", "第二個參數"));//增加參數2
try {
HttpPost postMethod = new HttpPost(baseUrl);//創建一個post請求
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //將參數填入POST Entity中
HttpResponse response = httpClient.execute(postMethod); //執行POST方法
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //獲取響應內容
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
5. java HttpPost怎麼傳遞參數
public class HttpURLConnectionPost {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
readContentFromPost();
}
public static void readContentFromPost() throws IOException {
// Post請求的url,與get不同的是不需要帶參數
URL postUrl = new URL("http://www.xxxxxxx.com");
// 打開連接
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");
// Post 請求不能使用緩存
connection.setUseCaches(false);
//設置本次連接是否自動重定向
connection.setInstanceFollowRedirects(true);
// 配置本次連接的Content-type,配置為application/x-www-form-urlencoded的
// 意思是正文是urlencoded編碼過的form參數
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 連接,從postUrl.openConnection()至此的配置必須要在connect之前完成,
// 要注意的是connection.getOutputStream會隱含的進行connect。
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
// 正文,正文內容其實跟get的URL中 '? '後的參數字元串一致
String content = "欄位名=" + URLEncoder.encode("字元串值", "編碼");
// DataOutputStream.writeBytes將字元串中的16位的unicode字元以8位的字元形式寫到流裡面
out.writeBytes(content);
//流用完記得關
out.flush();
out.close();
//獲取響應
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null){
System.out.println(line);
}
reader.close();
//該乾的都幹完了,記得把連接斷了
connection.disconnect();
}
(5)java調用post介面擴展閱讀:
關於Java HttpURLConnection使用
public static String sendPostValidate(String serviceUrl, String postData, String userName, String password){
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
log.info("POST介面地址:"+serviceUrl);
URL realUrl = new URL(serviceUrl);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
// 設置通用的請求屬性
httpUrlConnection.setRequestProperty("accept","*/*");
httpUrlConnection.setRequestProperty("connection", "Keep-Alive");
httpUrlConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
Base64 base64 = new Base64();
String encoded = base64.encodeToString(new String(userName+ ":" +password).getBytes());
httpUrlConnection.setRequestProperty("Authorization", "Basic "+encoded);
// 發送POST請求必須設置如下兩行
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(new OutputStreamWriter(httpUrlConnection.getOutputStream(),"utf-8"));
// 發送請求參數
out.print(postData);
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
//
// if (!"".equals(result)) {
// BASE64Decoder decoder = new BASE64Decoder();
// try {
// byte[] b = decoder.decodeBuffer(result);
// result = new String(b, "utf-8");
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
return result;
} catch (Exception e) {
log.info("調用異常",e);
throw new RuntimeException(e);
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException e){
log.info("關閉流異常",e);
}
}
}
}
6. java http post 怎麼設置 raw格式
調試微信推廣支持中二維碼生成api的介面,使用chrome瀏覽器的postman插件,post請求時有一個選項是form-data,或者raw,使用raw可以請求成功,from-data不知道怎麼組裝key和value所以一直失敗。非常不明白raw是什麼意思,google網路都沒有相關的解釋。後來研究發現,其實raw方式使用的是純字元串的數據上傳方式,所以在POST之前,可能需要手工的把一些json/text/xml格式的數據轉換成字元串,是一種post原始請求,區別於form-data這種常用的key-value方式。
public static String result; public static void httpTest() throws ClientProtocolException, IOException { String token = "XRhjxAJZG3rFlPLg"; String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token; String json = "{"action_name":"QR_LIMIT_SCENE","action_info":{"scene":{"scene_id":234}}}"; HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); StringEntity postingString = new StringEntity(json);// json傳遞 post.setEntity(postingString); post.setHeader("Content-type", "application/json"); HttpResponse response = httpClient.execute(post); String content = EntityUtils.toString(response.getEntity()); // Log.i("test",content); System.out.println(content); result = content; }
以上代碼中需要導入
import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils;
Android中自帶org.apache.http相關庫文件,所以可以快捷鍵(ctrl+shift+o)一次導入成功。