com.squareup.okhttp.ResponseBody Java Examples

The following examples show how to use com.squareup.okhttp.ResponseBody. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ZalyHttpClient.java    From wind-im with Apache License 2.0 6 votes vote down vote up
public byte[] postString(String url, String json) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, json);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example #2
Source File: NameFetcher.java    From RedisBungee with Eclipse Public License 1.0 6 votes vote down vote up
public static List<String> nameHistoryFromUuid(UUID uuid) throws IOException {
    String url = "https://api.mojang.com/user/profiles/" + uuid.toString().replace("-", "") + "/names";
    Request request = new Request.Builder().url(url).get().build();
    ResponseBody body = httpClient.newCall(request).execute().body();
    String response = body.string();
    body.close();

    Type listType = new TypeToken<List<Name>>() {
    }.getType();
    List<Name> names = RedisBungee.getGson().fromJson(response, listType);

    List<String> humanNames = new ArrayList<>();
    for (Name name : names) {
        humanNames.add(name.name);
    }
    return humanNames;
}
 
Example #3
Source File: SimpleRequest.java    From Auth0.Android with MIT License 6 votes vote down vote up
@Override
public void onResponse(Response response) {
    if (!response.isSuccessful()) {
        postOnFailure(parseUnsuccessfulResponse(response));
        return;
    }

    ResponseBody body = response.body();
    try {
        Reader charStream = body.charStream();
        T payload = getAdapter().fromJson(charStream);
        postOnSuccess(payload);
    } catch (IOException e) {
        final Auth0Exception auth0Exception = new Auth0Exception("Failed to parse response to request to " + url, e);
        postOnFailure(getErrorBuilder().from("Failed to parse a successful response", auth0Exception));
    } finally {
        closeStream(body);
    }
}
 
Example #4
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] postBytes(String url, byte[] bytes) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, bytes);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example #5
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] postString(String url, String json) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, json);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example #6
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] get(String url) throws Exception {
	ResponseBody body = null;
	try {
		Request request = new Request.Builder().url(url).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http get url={} error.{}", url, response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example #7
Source File: HttpApiBase.java    From iview-android-tv with MIT License 6 votes vote down vote up
private ResponseBody fetchFromNetwork(Uri url, int staleness) {
    Request.Builder builder = new Request.Builder();
    builder.url(url.toString());
    if (staleness > 0) {
        builder.cacheControl(allowStaleCache(staleness));
    }
    Request request = builder.build();
    client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(60, TimeUnit.SECONDS);
    Log.d(TAG, "Requesting URL:" + request.urlString());
    try {
        Response response = client.newCall(request).execute();
        if (response.cacheResponse() != null) {
            Log.d(TAG, "Cached response [" + response.code() + "]:" + request.urlString());
        } else {
            Log.d(TAG, "Network response [" + response.code() + "]:" + request.urlString());
        }
        if (response.isSuccessful()) {
            return response.body();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #8
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] postBytes(String url, byte[] bytes) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, bytes);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example #9
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] postString(String url, String json) throws IOException {
	ResponseBody body = null;
	try {
		RequestBody postBody = RequestBody.create(JSON, json);
		Request request = new Request.Builder().url(url).post(postBody).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http post error.{}", response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example #10
Source File: ZalyHttpClient.java    From openzaly with Apache License 2.0 6 votes vote down vote up
public byte[] get(String url) throws Exception {
	ResponseBody body = null;
	try {
		Request request = new Request.Builder().url(url).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http get url={} error.{}", url, response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example #11
Source File: ZalyHttpClient.java    From wind-im with Apache License 2.0 6 votes vote down vote up
public byte[] get(String url) throws Exception {
	ResponseBody body = null;
	try {
		Request request = new Request.Builder().url(url).build();
		Response response = httpClient.newCall(request).execute();
		if (response.isSuccessful()) {
			body = response.body();
			byte[] res = body.bytes();
			return res;
		} else {
			logger.error("http get url={} error.{}", url, response.message());
		}
	} finally {
		if (body != null) {
			body.close();
		}
	}
	return null;
}
 
Example #12
Source File: ShareRest.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
public void deleteContact(final String contactId, Callback<ResponseBody> deleteFollowerListener) {
    try {
        dexcomShareApi.deleteContact(getSessionId(), contactId).enqueue(new AuthenticatingCallback<ResponseBody>(deleteFollowerListener) {
            @Override
            public void onRetry() {
                dexcomShareApi.deleteContact(getSessionId(), contactId).enqueue(this);
            }
        });
    } catch (ShareException e) {
        deleteFollowerListener.onFailure(e);
    }
}
 
Example #13
Source File: HttpClientTest.java    From zsync4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testTransferListener() throws IOException, HttpError {
  final URI uri = URI.create("http://host/bla");

  final byte[] data = new byte[17];
  final ResponseBody body = mock(ResponseBody.class);
  when(body.contentLength()).thenReturn((long) data.length);
  when(body.source()).thenReturn(mock(BufferedSource.class));
  final InputStream inputStream = new ByteArrayInputStream(data);
  when(body.byteStream()).thenReturn(inputStream);

  final Request request = new Request.Builder().url(uri.toString()).build();
  final Response response = new Response.Builder().protocol(HTTP_1_1).body(body).request(request).code(200).build();

  final Call mockCall = mock(Call.class);
  when(mockCall.execute()).thenReturn(response);
  final OkHttpClient mockHttpClient = mock(OkHttpClient.class);
  when(mockHttpClient.newCall(any(Request.class))).thenReturn(mockCall);

  final EventLogHttpTransferListener listener = new EventLogHttpTransferListener();
  final InputStream in =
      new HttpClient(mockHttpClient).get(uri, Collections.<String, Credentials>emptyMap(), listener);
  final byte[] b = new byte[8];
  assertEquals(0, in.read());
  assertEquals(8, in.read(b));
  assertEquals(8, in.read(b, 0, 8));
  assertEquals(-1, in.read());
  in.close();

  final List<Event> events =
      ImmutableList.of(new Initialized(new Request.Builder().url(uri.toString()).build()), new Started(uri,
          data.length), new Transferred(1), new Transferred(8), new Transferred(8), Closed.INSTANCE);
  assertEquals(events, listener.getEventLog());
}
 
Example #14
Source File: OkHttpImageDownloader.java    From Android-Universal-Image-Loader-Modify with Apache License 2.0 5 votes vote down vote up
@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
	Request request = new Request.Builder().url(imageUri).build();
	ResponseBody responseBody = client.newCall(request).execute().body();
	InputStream inputStream = responseBody.byteStream();
	int contentLength = (int) responseBody.contentLength();
	return new ContentLengthInputStream(inputStream, contentLength);
}
 
Example #15
Source File: FollowerListAdapter.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@Override
public View getView(final int position, final View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.item_follower, null);
    }
    TextView followerName = (TextView) view.findViewById(R.id.follwerName);
    Button deleteButton = (Button) view.findViewById(R.id.deleteFollower);

    final ExistingFollower follower = list.get(position);

    followerName.setText(follower.ContactName);
    deleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Callback<ResponseBody> deleteFollowerListener = new Callback<ResponseBody>() {
                @Override
                public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
                    if (response.isSuccess()) {
                        Toast.makeText(context, gs(R.string.follower_deleted_succesfully), Toast.LENGTH_LONG).show();
                        list.remove(position);
                        notifyDataSetChanged();
                    } else {
                        Toast.makeText(context, gs(R.string.failed_to_delete_follower), Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    Toast.makeText(context, gs(R.string.failed_to_delete_follower), Toast.LENGTH_LONG).show();
                }
            };
            shareRest.deleteContact(follower.ContactId, deleteFollowerListener);
        }
    });
    return view;
}
 
Example #16
Source File: HttpApiBase.java    From iview-android-tv with MIT License 5 votes vote down vote up
private String extractBody(ResponseBody body) {
    if (body != null) {
        try {
            return body.string();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example #17
Source File: MainActivity.java    From StreetView with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    streetViewContainer = (ImageView) findViewById(R.id.streetImageContainer);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            StreetView streetView = new StreetView.Builder("ApiKey")
                    .pitch("-0.76")
                    .heading("80.0")
                    .size("600x450")
                    .fov("90")
                    .build();

            streetView.getStreetView(41.0421119, 29.0379787, new CallBack() {
                @Override
                public void onResponse(Response<ResponseBody> response, Retrofit retrofit, Bitmap bitmapStreetView) {
                    streetViewContainer.setImageBitmap(bitmapStreetView);
                }

                @Override
                public void onFailure(Throwable t) {
                    t.printStackTrace();
                }
            });
        }
    });
}
 
Example #18
Source File: FollowerListAdapter.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public View getView(final int position, final View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.item_follower, null);
    }
    TextView followerName = (TextView) view.findViewById(R.id.follwerName);
    Button deleteButton = (Button) view.findViewById(R.id.deleteFollower);

    final ExistingFollower follower = list.get(position);

    followerName.setText(follower.ContactName);
    deleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Callback<ResponseBody> deleteFollowerListener = new Callback<ResponseBody>() {
                @Override
                public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
                    if (response.isSuccess()) {
                        Toast.makeText(context, gs(R.string.follower_deleted_succesfully), Toast.LENGTH_LONG).show();
                        list.remove(position);
                        notifyDataSetChanged();
                    } else {
                        Toast.makeText(context, gs(R.string.failed_to_delete_follower), Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    Toast.makeText(context, gs(R.string.failed_to_delete_follower), Toast.LENGTH_LONG).show();
                }
            };
            shareRest.deleteContact(follower.ContactId, deleteFollowerListener);
        }
    });
    return view;
}
 
Example #19
Source File: FollowerListAdapter.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
@Override
public View getView(final int position, final View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.item_follower, null);
    }
    TextView followerName = (TextView) view.findViewById(R.id.follwerName);
    Button deleteButton = (Button) view.findViewById(R.id.deleteFollower);

    final ExistingFollower follower = list.get(position);

    followerName.setText(follower.ContactName);
    deleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Callback<ResponseBody> deleteFollowerListener = new Callback<ResponseBody>() {
                @Override
                public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
                    if (response.isSuccess()) {
                        Toast.makeText(context, "Follower deleted succesfully", Toast.LENGTH_LONG).show();
                        list.remove(position);
                        notifyDataSetChanged();
                    } else {
                        Toast.makeText(context, "Failed to delete follower", Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure(Throwable t) {
                    Toast.makeText(context, "Failed to delete follower", Toast.LENGTH_LONG).show();
                }
            };
            shareRest.deleteContact(follower.ContactId, deleteFollowerListener);
        }
    });
    return view;
}
 
Example #20
Source File: ShareRest.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public void uploadBGRecords(final ShareUploadPayload bg, Callback<ResponseBody> callback) {
    dexcomShareApi.uploadBGRecords(getSessionId(), bg).enqueue(new AuthenticatingCallback<ResponseBody>(callback) {
        @Override
        public void onRetry() {
            dexcomShareApi.uploadBGRecords(getSessionId(), bg).enqueue(this);
        }
    });
}
 
Example #21
Source File: ToStringConverterFactory.java    From materialup with Apache License 2.0 5 votes vote down vote up
@Override
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
    if (String.class.equals(type)) {
        return new Converter<ResponseBody, String>() {
            @Override
            public String convert(ResponseBody value) throws IOException {
                return value.string();
            }
        };
    }
    return null;
}
 
Example #22
Source File: CreateActivity.java    From materialup with Apache License 2.0 5 votes vote down vote up
private void handleRes(ResponseBody r) {
    try {
        System.out.println(r.string());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #23
Source File: ResponseUtilsTest.java    From Auth0.Android with MIT License 5 votes vote down vote up
@Test
public void shouldCloseBody() throws Exception {
    ResponseBody body = mock(ResponseBody.class);
    ResponseUtils.closeStream(body);

    verify(body).close();
}
 
Example #24
Source File: BaseRequestTest.java    From Auth0.Android with MIT License 5 votes vote down vote up
private Response createJsonResponse(String jsonPayload, int code) {
    Request request = new Request.Builder()
            .url("https://someurl.com")
            .build();

    final ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), jsonPayload);
    return new Response.Builder()
            .request(request)
            .protocol(Protocol.HTTP_1_1)
            .body(responseBody)
            .code(code)
            .build();
}
 
Example #25
Source File: BaseRequestTest.java    From Auth0.Android with MIT License 5 votes vote down vote up
private Response createBytesResponse(byte[] content, int code) {
    Request request = new Request.Builder()
            .url("https://someurl.com")
            .build();

    final ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/octet-stream; charset=utf-8"), content);
    return new Response.Builder()
            .request(request)
            .protocol(Protocol.HTTP_1_1)
            .body(responseBody)
            .code(code)
            .build();
}
 
Example #26
Source File: VideoPlayActivity.java    From BlueBoard with Apache License 2.0 5 votes vote down vote up
private void videoFormZhuZhan() {
    final Observable<NewAcVideo> getVideo = NewAcApi.getNewAcVideo().onResult(mVideoId);
    final Observable<Response<ResponseBody>> getDanmaku = NewAcApi.getNewAcDanmaku().onResult(mVideoId);

    Subscription subscription = getDanmaku.subscribeOn(Schedulers.io())
            .flatMap(new Func1<Response<ResponseBody>, Observable<NewAcVideo>>() {
                @Override
                public Observable<NewAcVideo> call(Response<ResponseBody> response) {
                    try {
                        danmuku(new BufferedInputStream(response.body().byteStream()));

                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {

                    }
                    return getVideo;
                }
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<NewAcVideo>() {
                @Override
                public void call(NewAcVideo newAcVideo) {
                    List<NewAcVideo.DataEntity.FilesEntity> list = newAcVideo.getData().getFiles();
                    Collections.reverse(list);
                    mUri = Uri.parse(list.get(0).getUrl().get(0));
                    mOkVideoView.setVideoUri(mUri, false);
                    Log.w(TAG, "call: " + mUri.toString());
                }
            });
    mCompositeSubscription.add(subscription);
}
 
Example #27
Source File: OkHttpStack.java    From SimplifyReader with Apache License 2.0 5 votes vote down vote up
private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();
    ResponseBody body = r.body();

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(r.header("Content-Encoding"));

    if (body.contentType() != null) {
        entity.setContentType(body.contentType().type());
    }
    return entity;
}
 
Example #28
Source File: HttpApiBase.java    From iview-android-tv with MIT License 5 votes vote down vote up
protected InputStream fetchStream(Uri url, int staleness) {
    ensureCache();
    ResponseBody body = fetchFromNetwork(url, staleness);
    if (body != null) {
        try {
            return body.byteStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example #29
Source File: NightscoutUploader.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
private void postDeviceStatus(NightscoutService nightscoutService, String apiSecret) throws Exception {
    JSONObject json = new JSONObject();
    json.put("uploaderBattery", getBatteryLevel());
    RequestBody body = RequestBody.create(MediaType.parse("application/json"), json.toString());
    Response<ResponseBody> r;
    if (apiSecret != null) {
        r = nightscoutService.uploadDeviceStatus(apiSecret, body).execute();
    } else
        r = nightscoutService.uploadDeviceStatus(body).execute();
    if (!r.isSuccess()) throw new UploaderException(r.message(), r.code());
}
 
Example #30
Source File: BgUploader.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
public void upload(ShareUploadPayload bg) {
    shareRest.uploadBGRecords(bg, new Callback<ResponseBody>() {
        @Override
        public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
            // This should probably be pulled up into BgSendQueue or NightscoutUploader
            // where errors can be handled properly.
        }

        @Override
        public void onFailure(Throwable t) {
            UserError.Log.d(TAG, "Error uploading Share records: "+ t.getMessage());
        }
    });
}