㈠ java sendPost請求方法如何加入參數
/**
* 向指定 URL 發送POST方法的請求
*
* @param url
* 發送請求的 URL
* @param param
* 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
* @return 所代表遠程資源的響應結果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發送請求參數
out.print(param);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送 POST 請求出現異常!"+e);
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
㈡ 怎麼用java程序以post方式發送表單參數給伺服器
POST方式發送請求示例:
Stringfullurl=url;
//打開連接
URLConnectionconn=newURL(fullurl).openConnection();
//設置通用的請求屬性
conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("connection","Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/42.0.2311.90Safari/537.36");
//發送POST請求必須設置下面兩行
conn.setDoInput(true);
conn.setDoOutput(true);
try(
//獲取URLConnection對象對應的輸出流
PrintWriterout=newPrintWriter(conn.getOutputStream());){
out.print(parm);//發送請求參數(key1=value1&key2=value2)
out.flush();//flush輸出流的緩沖
}catch(Exceptione){}
//獲取響應頭欄位
Map<String,List<String>>map=conn.getHeaderFields();
//根據輸入流讀取響應數據
InputStreamis=conn.getInputStream();
僅供參考。
㈢ 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();
}
關於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);
}
}
}
}
㈣ 如何用Java通過POST方法向HTTP介面傳遞數據
這是corejava2的例子x0dx0aURLConnectionconnection=url.openConnection();//url為http伺服器地址x0dx0aconnection.setDoOutput(true);x0dx0aPrintWriteroutx0dx0a=newPrintWriter(connection.getOutputStream());//獲得輸出流x0dx0a//向伺服器傳遞參數x0dx0aEnumerationenum=nameValuePairs.keys();x0dx0awhile(enum.hasMoreElements())x0dx0a{Stringname=(String)enum.nextElement();x0dx0aStringvalue=nameValuePairs.getProperty(name);x0dx0acharch;x0dx0aif(enum.hasMoreElements())ch='&'elsech='\n'x0dx0aout.print(name+"="x0dx0a+URLEncoder.encode(value)+ch);x0dx0aSystem.out.println(name+value);x0dx0a}x0dx0ax0dx0aout.close();x0dx0a//獲取輸入流x0dx0aBufferedReaderin;x0dx0atryx0dx0a{in=newBufferedReader(newx0dx0aInputStreamReader(connection.getInputStream()));x0dx0a}x0dx0acatch()x0dx0a{InputStreamerrx0dx0a=((HttpURLConnection)connection).getErrorStream();x0dx0aif(err==null)throwexception;x0dx0ain=newBufferedReader(newInputStreamReader(err));x0dx0a}x0dx0aStringBufferresponse=newStringBuffer();x0dx0aStringline;x0dx0a//讀取數據x0dx0awhile((line=in.readLine())!=null)x0dx0aresponse.append(line+"\n");x0dx0ax0dx0ain.close();x0dx0areturnresponse.toString();x0dx0a}x0dx0a}
㈤ java 測試post請求 在body裡面傳遞參數怎麼設置,怎麼接收
package wzh.Http;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.URL;import java.net.URLConnection;import java.util.List;import java.util.Map;public class HttpRequest { /** * 向指定URL發送GET方法的請求 * * @param url * 發送請求的URL * @param param * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return URL 所代表遠程資源的響應結果 */ public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打開和URL之間的連接 URLConnection connection = realUrl.openConnection(); // 設置通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立實際的連接 connection.connect(); // 獲取所有響應頭欄位 Map> map = connection.getHeaderFields(); // 遍歷所有的響應頭欄位 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("發送GET請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定 URL 發送POST方法的請求 * * @param url * 發送請求的 URL * @param param * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return 所代表遠程資源的響應結果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection conn = realUrl.openConnection(); // 設置通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 獲取URLConnection對象對應的輸出流 out = new PrintWriter(conn.getOutputStream()); // 發送請求參數 out.print(param); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("發送 POST 請求出現異常!"+e); e.printStackTrace(); } //使用finally塊來關閉輸出流、輸入流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return result; } }//函數調用時填入URL和參數(參數非必須)就可以獲取返回的數據,發送post請求調用示例String result=HttpRequest.sendPost("/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=json&ak=","")
㈥ java post時設置參數的問題求助
url,[data],[callback],[type]
其中url為必填項,其值為請求的地址
data為可填可不填項,其值為要傳送的key/value的值
callback為可填可不填項,為回調函數,當請求成功後,執行的內容
type為可填可不填項,為返回的數據格式
㈦ java post請求參數怎麼寫
//serverURL url地址
HttpPost httpPost = new HttpPost(serverURL);
//param 為參數
StringEntity entity = new StringEntity(param);
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
還可以用map作為參數
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
if(param!=null){
Set set = param.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
Object value = param.get(key);
formparams.add(new BasicNameValuePair(key.toString(), value.toString()));
}
}