java setparams方法_Java HttpURLConnection post set params 设置请求参数的三种方法 实践总结...

时间:2025-03-22 09:26:14

/**

*@param pathurl

*@param paramsStr

*@return

*/

private static String postUrlBackStr(String pathurl, String paramsStr) {

String backStr = "";

InputStream inputStream = null;

ByteArrayOutputStream baos = null;

try {

URL url = new URL(pathurl);

HttpURLConnection connection = (HttpURLConnection) ();

// 设定请求的方法为"POST",默认是GET

("POST");

(50000);

(50000);

// User-Agent IE11 的标识

("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.3; Trident/7.0;rv:11.0)like Gecko");

("Accept-Language", "zh-CN");

("Connection", "Keep-Alive");

("Charset", "UTF-8");

/**

* 当我们要获取我们请求的http地址访问的数据时就是使用().read()方式时我们就需要setDoInput(true),

根据api文档我们可知doInput默认就是为true。我们可以不用手动设置了,如果不需要读取输入流的话那就setDoInput(false)。

当我们要采用非get请求给一个http网络地址传参 就是使用().write() 方法时我们就需要setDoOutput(true), 默认是false

*/

// 设置是否从httpUrlConnection读入,默认情况下是true;

(true);

// 设置是否向httpUrlConnection输出,如果是post请求,参数要放在http正文内,因此需要设为true, 默认是false;

(true);

(false);

/**

* the first way to set params

* OutputStream

*/

/* byte[] bytesParams = ();

// 发送请求params参数

OutputStream outStream=();

(bytesParams);

();

*/

/**

* the second way to set params

* PrintWriter

*/

/* PrintWriter printWriter = new PrintWriter(());

//PrintWriter printWriter = new PrintWriter(new OutputStreamWriter((),"UTF-8"));

// 发送请求params参数

(paramsStr);

();*/

/**

* the third way to set params

* OutputStreamWriter

*/

OutputStreamWriter out = new OutputStreamWriter(

(), "UTF-8");

// 发送请求params参数

(paramsStr);

();

();//

int contentLength = ();

if (() == 200) {

inputStream = ();//会隐式调用connect()

baos = new ByteArrayOutputStream();

int readLen;

byte[] bytes = new byte[1024];

while ((readLen = (bytes)) != -1) {

(bytes, 0, readLen);

}

backStr = ();

(TAG, "backStr:" + backStr);

} else {

(TAG, "请求失败 code:" + ());

}

} catch (MalformedURLException e) {

();

} catch (IOException e) {

();

} finally {

try {

if (baos != null) {

();

}

if (inputStream != null) {

();

}

} catch (IOException e) {

();

}

}

return backStr;

}