发出HTTP请求并获得HTTP响应的过程如下:
(1)定义HTTP请求HttpPut(HttpPost/HttpGet/HttpDelete)等;
(2)定义各种Header,并加入HttpPut中;
(3)定义HttpEntitty,将要发送的XML字符串加入HttpEntity,并将HttpEntity加入HttpPut;
(4)定义HttpClient,执行HttpPut,并返回HttpResponse;
(5)从HttpResponse中获得StatusCode;
(6)从HttpResponse中获得各种Header;
(7)从HttpResponse中获得HttpEntity,并获得其中的字符串输出。
代码如下:
// 修改队列参数 public static void modify_queue_attributes(){ // 定义HttpClient HttpClient httpClient = new DefaultHttpClient(); // Uri String hs = host + "/" + queName +"?Metaoverride=true"; // 定义HttpPut HttpPut httpPut = new HttpPut(hs); // 各种Header httpPut.setHeader("Date", time); System.out.println("Date:" + time); httpPut.setHeader("x-mqs-version", version); System.out.println("x-mqs-version:" + version); httpPut.setHeader("Authorization", auth); System.out.println("Authorization:" + auth); httpPut.setHeader("Content-Type", content_type); System.out.println("Content-Type:" + content_type); // 消息体内容(XML格式) StringBuilder req = new StringBuilder(); String s = new String(""); s = " "; req.append(s); s = ""; req.append(s); s = " "; req.append(s); System.out.println(); System.out.println(req); // 定义HttpEntity HttpEntity entity; try{ // StringEntity entity = new StringEntity(req.toString()); // 为HttpPut设置Entity httpPut.setEntity(entity); // HttpClient执行HttpPut,并返回HttpResponse HttpResponse httpResponse = httpClient.execute(httpPut); // 获得StatusCode int statusCode = httpResponse.getStatusLine().getStatusCode(); System.out.println("Status Code: " + statusCode); // 获得HttpResponse的各种Header Header[] header; header = httpResponse.getHeaders("Content-Length"); if (header.length != 0){ // System.out.println(header[0].toString()); } header = httpResponse.getHeaders("Connection"); if (header.length != 0){ // System.out.println(header[0].toString()); } header = httpResponse.getHeaders("Date"); if (header.length != 0){ // System.out.println(header[0].toString()); } header = httpResponse.getHeaders("Server"); if (header.length != 0){ // System.out.println(header[0].toString()); } header = httpResponse.getHeaders("x-mqs-request-id"); if (header.length != 0){ // System.out.println(header[0].toString()); } header = httpResponse.getHeaders("x-mqs-version"); if (header.length != 0){ // System.out.println(header[0].toString()); } // 获得HttpResponse的HttpEntity并以字符串形式输出 HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null){ InputStream instreams = httpEntity.getContent(); String str = ConvertStreamToString(instreams); System.out.println("Response:" + "\n" + str); } } catch(Exception e){ System.out.println("Error=" + e.toString()); } }120 "; req.append(s); s = "1024 "; req.append(s); s = "120 "; req.append(s); s = "60 "; req.append(s); s = "
返回结果为:
Status Code: 403Response:SignatureDoesNotMatch
The request signature we calculated does not match the signature you provided. Check your key and signing method. 53D60FE4048A936A361D8ABA http://huvaw6yih3.mqs-cn-hangzhou.aliyuncs.com