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去调用。

你可能感兴趣的:(java)