Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ant.junior.webapi;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.protocol.BasicHttpContext;
- import org.apache.http.protocol.HttpContext;
- import android.util.Base64;
- public class Api {
- HttpClient httpClient = new DefaultHttpClient();
- String baseApiUrl;
- HttpPost httpPost;
- String result;
- HttpContext localContext = new BasicHttpContext();
- HttpGet httpGet;
- HttpResponse response;
- String headerRequest;
- public Api(String baseUrl){
- this.baseApiUrl = baseUrl;
- this.result = "";
- this.headerRequest = "";
- }
- public void updateUrl(String url){
- //Update the get
- httpGet = new HttpGet(this.baseApiUrl+url);
- //Update the post
- httpPost = new HttpPost(this.baseApiUrl+url);
- }
- public void updateHeader(String user, String password){
- httpGet.setHeader("Authorization", "Basic " + Base64.encodeToString((user+":"+password).getBytes(), Base64.NO_WRAP));
- httpPost.setHeader("Authorization", "Basic " + Base64.encodeToString((user+":"+password).getBytes(), Base64.NO_WRAP));
- }
- public String get(){
- System.out.println();
- try {
- this.response = httpClient.execute(httpGet, localContext);
- } catch (ClientProtocolException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- BufferedReader reader = null;
- try {
- reader = new BufferedReader(
- new InputStreamReader(
- response.getEntity().getContent()
- )
- );
- } catch (IllegalStateException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- String line = "";
- try {
- while ((line = reader.readLine()) != null){
- result += line + "\n";
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(result);
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement