Java发送http请求 (get 与 post方法请求)

转载见:http://www.jiucool.com/java-sending-http-requests-get-and-post-method-request/


除了上述方法外,还可以这样:

//首先是url的标准配置方法

URI uri = URIUtils.createURI(("http","localhost",8080, "/this is the path/this is the subPath",

                                                     "partOne of the queryString" + URLEncoder.encode("partTwo of the queryString which needed to be decorded!","UTF-8"), null);             
注意: 如果在url中有非法字符,请使用URLEncoder.encode(String , String)方法进行编码,如上面蓝色字体所示。

//其次是需要post的字符串

String strs = "this is the string needing to be sent!";

//再次则是新建HttpPost的对象,并将需要post的字符串添加到其中。

HttpPost httpPost = new HttpPost(uri);

StringEntity myEntity = new StringEntity(strs);

httpPost.setEntity(myEntity);

//最后设置HttpClient,用来完成http的post请求

HttpClient httpClient = new DefaultHttpClient();

//执行请求

HttpResponse response = client.execute(httpGet);
//根据返回的response结果,查看

i.查看其状态           System.out.println(response.getStatusLine());
ii.查看返回的实体            System.out.println(EntityUtils.toString(response.getEntity(), HTTP.UTF_8));

注意上面将HttpEntity 对象转成String的方法: EntityUtils.toString(response.getEntity, HTTp.UTF_8)


同样地,如果有Get,Delete,Put请求,也可以使用对应的HttpGet/HttpDelete/HttpPut对象,然后使用HttpClient去调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值