Java Post请求的一个例子,问几个问题

鸣鸣Amadues 2016-10-12 03:17:37

// HTTP POST request
private void sendPost() throws Exception {

String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

//print result
System.out.println(response.toString());

}
...全文
274 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
进阶的攻城狮 2016-10-14
  • 打赏
  • 举报
回复
上游接口接受数据是这么接受的 BufferedReader bf=req.getReader(); String temp=null; StringBuilder sb=new StringBuilder(); while((temp=bf.readLine())!=null){ sb.append(temp); } System.out.println(sb.toString()); 从流里面读取,也可以直接 @RequestMapping("queryList") @ResponseBody public void queryList(@RequestBody Map<String ,String> map){ }直接转换成map,这个要配置spring的转换器,里面其实就是上面的
tianfang 2016-10-14
  • 打赏
  • 举报
回复
引用 1 楼 Raffin 的回复:
user agent,我看它填了mozilla,那是不是还要把其他浏览器都填上,我的需求是Java程序里发送http请求,应该和浏览器是无关的。 response对象这边怎么获取并解析?是程序的哪一段?是不是那个getInputStream?
部分服务器要根据user agent判断浏览器类型,你填上一种就可以了 response对象:没有对象,只有报文,response就是返回报文
QiuRiMangCao 2016-10-13
  • 打赏
  • 举报
回复
引用 2 楼 鸣鸣小恶魔的回复:
还有这一段是起到什么作用?是必须的嘛? con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
浏览器接收语言的类型
鸣鸣Amadues 2016-10-12
  • 打赏
  • 举报
回复
还有这一段是起到什么作用?是必须的嘛? con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
鸣鸣Amadues 2016-10-12
  • 打赏
  • 举报
回复
user agent,我看它填了mozilla,那是不是还要把其他浏览器都填上,我的需求是Java程序里发送http请求,应该和浏览器是无关的。 response对象这边怎么获取并解析?是程序的哪一段?是不是那个getInputStream?

67,515

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧