java HttpPost怎么传递参数

最好实例...

这里有两种方法:

1、有时候考虑请求接口时,参数的形式是这样的:如"key1=value1&key2=value2"

这样http get和post的方法都可以用同样的结构来作为参数,于是http post的方法请求服务器数据时可以用这样的方法来实现。

2、new BasicNameValuePair(keys[i], values[i]),这里写参数。

扩展资料:

httpPost其实在服务端模拟浏览器向其它接口发送服务的,一般情况下和httpclient,或者jsonp联合使用,可以把它理解为浏览器就行了,里面封装了http协议的一些东西,所以要对http协议有一定的了解。

超文本传输协议(HTTP)的设计目的是保证客户机与服务器之间的通信。HTTP 的工作方式是客户机与服务器之间的请求-应答协议。web 浏览器可能是客户端,而计算机上的网络应用程序也可能作为服务器端。

在客户机和服务器之间进行请求-响应时,两种最常被用到的方法是:GET 和 POST。

GET - 从指定的资源请求数据。POST - 向指定的资源提交要被处理的数据。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2019-10-27

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);

}

}

}

}

本回答被网友采纳
第2个回答  推荐于2017-09-22

JAVA HttpURLConnection Post方式提交传递参数 的示例如下:

package wzq.j2se;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
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.wangzhiqiang87.cn");
        // 打开连接
        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参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
        // 进行编码
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
        // 要注意的是connection.getOutputStream会隐含的进行connect。
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection
                .getOutputStream());
        // The URL-encoded contend
        // 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
        String content = "account=" + URLEncoder.encode("一个大肥人", "UTF-8");
        content +="&pswd="+URLEncoder.encode("两个个大肥人", "UTF-8");;
        // 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();
}
}

第3个回答  2013-03-27
/**
* 获取请求参数键值对数组 </p>
*
* @param request
* HttpServletRequest对象
* @return HashMap<String,String> 分请求参数键值对数组
* @throws UnsupportedEncodingException
*/
private HashMap<String, String> parseReqParam(HttpServletRequest request) {
// 取消对请求串的UTF-8编码,防止不同浏览器中发送请求时进行默认编码处理导致的转码失败
String reqParamStr = request.getQueryString();
// 请求参数为空
if (reqParamStr == null || reqParamStr.isEmpty()) {
return null;
}
HashMap<String, String> paramList = new HashMap<String, String>();
// 将各组键值对取出
String[] queryParam = reqParamStr.split("&");
int length = queryParam.length;
// 将键值对保存
for (int i = 0; i < length; i++) {
String param = queryParam[i];
int index = param.indexOf("=");
// 存在键值对的话
if (index != -1) {
String paramKey = param.substring(0, index);
String paramValue = param.substring(index + 1, param.length());
paramList.put(paramKey.toUpperCase(), paramValue); // key转换成大写保存
}
}// end for... KVP in queryParam
return paramList;
}
第4个回答  2013-03-26
这种是简单的 www.aaa.com/index.jsp?a=b&c=d传参
//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()));
}
}本回答被网友采纳
相似回答