1. 程式人生 > >Httpclient 請求帶Authorization(授權)的REST API 返回JSON資料

Httpclient 請求帶Authorization(授權)的REST API 返回JSON資料

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import javax.xml.bind.DatatypeConverter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.*; /** * Created by xenia on 2017/6/6.
*/
public class JavaNetURLRESTFulClient {
    public static void main(String[] args) throws ClientProtocolException, IOException {
        //認證資訊物件,用於包含訪問翻譯服務的使用者名稱和密碼
String path = "http://************";
        //1.建立客戶端訪問伺服器的httpclient物件   開啟瀏覽器
HttpClient httpclient = new DefaultHttpClient();
        //2.以請求的連線地址建立get請求物件     瀏覽器中輸入網址
HttpGet httpget = new HttpGet(path); //username:password--->訪問的使用者名稱,密碼,並使用base64進行加密,將加密的位元組資訊轉化為string型別,encoding--->token String encoding = DatatypeConverter.printBase64Binary("username:password".getBytes("UTF-8")); httpget.setHeader("Authorization", "Basic " +encoding); //3.向伺服器端傳送請求 並且獲取響應物件 瀏覽器中輸入網址點選回車 HttpResponse response = httpclient.execute(httpget); //4.獲取響應物件中的響應碼 StatusLine statusLine = response.getStatusLine();//獲取請求物件中的響應行物件 int responseCode = statusLine.getStatusCode();//從狀態行中獲取狀態碼 System.out.println(responseCode); if (responseCode == 200) { //5. 可以接收和傳送訊息 HttpEntity entity = response.getEntity(); //6.從訊息載體物件中獲取操作的讀取流物件 InputStream input = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(input)); String str1 = br.readLine(); String result = new String(str1.getBytes("gbk"), "utf-8"); System.out.println("伺服器的響應是:" + result); br.close(); input.close(); } else { System.out.println("響應失敗!"); } } }
執行結果:
200
伺服器的響應是:{"events":375383}
其中:{"events":375383}是請求API的響應體(返回的JSON資料)