httoclient类中的postmethod方法中用需要传入的参数是什么

2024-11-30 19:13:45
推荐回答(3个)
回答1:

  用PostMethod 模拟http post请求,需要解决传递字符串,文件等需求。
  httpclient对此,提供了对应实现,实现方法关键在:RequestEntity。
  示例:
  RequestEntity requestEntity = newStringRequestEntity(text);
  post.setRequestEntity(requestEntity);
  示例中,是传递一个普通字符型参数。
  这个方法代替了以前直接设置Request body。
  RequestEntity是一个接口,有很多实现:  ByteArrayRequestEntity, FileRequestEntity, InputStreamRequestEntity, MultipartRequestEntity, StringRequestEntity
  基本上从名字上就可以直接看出功能,可以从字符串,流,文件,字节数组中产生request body。
  还有更复杂的Multipart,就是夹杂文件和普通字段的提交。
  示例如下:  Part[] parts = {new StringPart("source", "695132533"), new StringPart("status", URLEncoder.encode(status, "utf-8")), filePart};  postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

回答2:

url 和 post的参数,下面是我搜到的,你参考下吧

private static void post() throws IOException{
URL url = new URL(" http://www.baidu.com");// 提交地址
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);// 打开写入属性
httpURLConnection.setDoInput(true);// 打开读取属性
httpURLConnection.setRequestMethod("POST");// 设置提交方法
httpURLConnection.setRequestProperty("Content-Type","text/xml;charset=UTF-8");//
httpURLConnection.setRequestProperty("SOAPAction", " http://WebXml.com.cn/getWeatherbyCityName");
httpURLConnection.setRequestProperty("User-Agent", "Jakarta Commons-HttpClient/3.1");
httpURLConnection.setConnectTimeout(50000);// 连接超时时间
httpURLConnection.setReadTimeout(50000);
httpURLConnection.connect();

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream()));
out.write("name=1&pwd=2");
out.flush();
out.close();

//读取post之后的返回值
BufferedReader in = new BufferedReader(new InputStreamReader((InputStream) httpURLConnection.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
System.out.println("client:" + sb.toString());
httpURLConnection.disconnect();//断开连接
}

回答3:

url地址