when call yandex api It gives me 403 Forbidden by retrofit - retrofit

When I call this link
https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20151201T195234Z.a35326958c23a7a8.51da9f9c1ffe2d901f1ee0e4bf3cfdadfe19b3f8&ui=ru&text=apple&lang=en-ru on my browser it works, but when I call it using retrofit It gives me 403 Forbidden. Вut that I get only when I do not use the key in retrofit. When I use key, I get no callback by debug. Please help, I am suffering for the second week
I use retorfit so :
API
public interface APIService {
#GET("translate")
Call<Repo> loadRepo(
#Query(value = "key", encoded = true) String key ,
#Query("ui") String ui,
#Query("text") String text,
#Query("lang") String lang1) };
Repo r;
String text="apple"; String ui="ru";
String key="trnsl.1.1.20151201T195234Z.a35326958c23a7a8.51da9f9c1ffe2d901f1ee0e4bf3cfdadfe19b3f8";
String lang1="en-ru";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://translate.yandex.net/api/v1.5/tr.json/")
.addConverterFactory(GsonConverterFactory.create())
// .client(httpClient)
.build();
service = retrofit.create(APIService.class);
service.loadRepo( URLEncoder.encode(key), ui, text, lang1).enqueue(new Callback<Repo>() {
#Override
public void onResponse(Response<Repo> response, Retrofit retrofit) {
r = response.body();
int a = 1; // under debug here I look response and see 403 Forbidden
}
#Override
public void onFailure(Throwable t) {
}
});

Related

how to handle http response streamly by vertx http client?

#Slf4j
public class DownloadImg {
private final WebClient webClient;
private final Vertx vertx;
public DownloadImg(Vertx vertx) {
WebClientOptions newOptions = new WebClientOptions();
newOptions.setDefaultPort(12345);
newOptions.setDefaultHost("localhost");
webClient = WebClient.create(vertx,newOptions);
this.vertx = vertx;
}
public void download(String scm, String version) {
String file = String.format("/%s_%s.tar.gz", scm.replace("/", "."), version);
webClient.get("url_for_file")
.send(it -> {
it.result();// i acully
});
}
}
I do get all the file data, but I want to handle those data by stream API in case the file is too large or OOM exception.
any idea?

HttpClient Await PostAsync not completed

I have an asmx Web Service and I am using async Task. My problem is whenever I reached on the PostAsync statement it will just end there and fire a result to the browser with an empty result. Which is not I want. I tried passing the httpclient as a parameter to my service class thinking it may solved the issue.
I tried putting ConfigureAwait(false) and it gives a result however I don't want this because I need to return the value to the user. If I use ConfigurAwait(false) it will return an empty result to the browser even if it it still not completed. Am I doing this right? Thanks
in my webmethod
public class WebService1 : WebService
{
HttpClient Client = new HttpClient();
XDocument doc = new XDocument();
[WebMethod]
private async Task<String> Sample1(string a, int b)
{
myServiceClass _ms = new myServiceClass(Client);
var message = await _ms.GetResponseMessageAsync(a,b);
doc = await _ms.ReadResponseAsync(message); // It will not reach here if I don't use ConfigureAwait(false)
return JsonConvert.SerializeObject(doc);
}
}
myServiceClass.cs
public class myServiceClass
{
HttpClient _client;
public myServiceClass(HttpClient client)
{
_client = client;
}
public async Task<HttpResponseMessage> GetResponseMessageAsync(string a, int b)
{
HttpResponseMessage message;
httpcontent = (a,encoding.UTF8,"text/xml"); //This is just a sample content
message = await _client.PostAsync(UrlString, httpcontent); //<= here it stops and return empty result if there is no ConfigureAwait(false).
if (!message.IsSuccessStatusCode)
{
throw new HttpRequestException($"Cannot connect to api: {message.StatusCode} , {message.ReasonPhrase}");
}
return message; // It will not reach here if I don't use ConfigureAwait(false)
}
}

Pact Basic test fails

I am trying a simple pact test but its failing giving the error. Below is my code. Is there any issue with the way I'm trying to call pact.
ERROR:
groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object The current character read is 'T' with an int value of 84
CODE
public class PactTest1 {
#Rule
//public PactProviderRule rule = new PactProviderRule("assessments", this);
public PactProviderRule provider = new PactProviderRule("test_provider", "localhost", 8080, this);
#Pact(state = "default", provider = "test_provider", consumer = "test_consumer")
public PactFragment createFragment(PactDslWithProvider builder) {
Map<String, String> headers = new HashMap<>();
headers.put("content-type", "application/json");
return builder
.given("test GET")
.uponReceiving("GET REQUEST")
.path("/assessments")
.method("GET")
.willRespondWith()
.status(200)
.headers(headers)
.body("Test Successful")
.toFragment();
}
#Test
#PactVerification("test_provider")
public void runTest() {
final RestTemplate call = new RestTemplate();
// when
final String response = call.getForObject(provider.getConfig().url()+"/assessments", String.class);
assertEquals(response, "Test Successful");
}
}
It worked after the changed the header content type to text/json. However I'm not able to find the pact file. Where can I find it?

Basic Authentication with Retrofit

I am trying to build a client for a REST API using Retrofit. The API uses basic auth and I have been unable to authenticate using Retrofit.
I tested the API using the curl below and it works as expected
curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{some_json}' -u api_key: https://apitest.com/api/v1/customers
Below is the Retrofit client
public interface UserService {
String HOST = "https://apitest.com";
public static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
public static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(HOST)
.addConverterFactory(GsonConverterFactory.create());
/*
* CREATE/UPDATE User
*/
#POST("api/v1/customers")
Call<UserAPIResponse> userUpdate(#Body UserUpdateRequest userUpdateRequest);
static UserService newInstance(String userAPIKey) {
String credentials = userAPIKey + ":";
final String basic = "Basic "+ Base64.encodeBase64(credentials.getBytes());
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", basic);
requestBuilder.header("Accept", "application/json");
requestBuilder.method(original.method(),original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(BlueshiftUserService.class);
}
When I call updateUser on the UserService
Response<UserAPIResponse> response = UserService.userUpdate(userUpdateRequest).execute();
The response.code is 401 (unauthorized/authentication failed)
The curl command with -u and the same credentials works as expected.
The issue was with the credentials encoding. I wasnt sending it as string.
byte[] encodedAuth= Base64.encodeBase64(credentials.getBytes());
final String basic = "Basic " + new String(encodedAuth);
use these libraries in Gradle file
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.3.0'
compile 'com.cookpad.android.rxt4a:rxt4a:0.9.0'
compile 'io.reactivex:rxjava:1.0.12'
and put this classes in your project
public class ServiceGenerator {
private static final String TAG = erviceGenerator.class.getSimpleName();
public static final int READ_TIMEOUT = 10000;
public static final int CONNECT_TIMEOUT = 100000;
// No need to instantiate this class.
private ServiceGenerator(){}
public static <S> S createService(Class<S> serviceClass, String
endpoint) {
// Call basic auth generator method without user and pass
return createService(serviceClass, endpoint, null, null); }
public static <S> S createService(Class<S> serviceClass, String
endpoint, String username, String password) {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
okHttpClient.setConnectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
// Set endpoint url and use OkHTTP as HTTP client
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(endpoint)
.setConverter(new GsonConverter(new Gson()))
.setClient(new OkClient(okHttpClient));
if (username != null && password != null) {
// Concatenate username and password with colon for authentication
final String credentials = username + ":" + password;
builder.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
// Create Base64 encoded string
String string = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
request.addHeader("Authorization", string);
request.addHeader("Accept", "application/json");
}
});
}
RestAdapter adapter = builder.build();
return adapter.create(serviceClass); } }
and this interface
public class TodolyClient {
private static final String TAG = TodolyClient.class.getSimpleName();
public static final String ENDPOINT = "your base URL";
public interface TodolyService {
#GET("/wp-json/wc/v2/products")(your remaining url)
Observable<Object> isAuthenticated();
}
}
and call the below method in your main activity
private void createProject() {
final TodolyClient.TodolyService service =ServiceGenerator.createService(
TodolyClient.TodolyService.class, TodolyClient.ENDPOINT, "your user name",
"your password");
Observable<Object> observable = service.isAuthenticated();
AndroidCompositeSubscription compositeSubscription = new AndroidCompositeSubscription();
observable
.lift(new OperatorAddToCompositeSubscription<Object>(compositeSubscription))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Object>() {
#Override
public void onNext(Object project) {
android.util.Log.d(TAG, "onNext: "+project.toString());
}
#Override
public void onCompleted() {
android.util.Log.d(TAG, "onNext:commm " );
}
#Override
public void onError(Throwable e) {
android.util.Log.d(TAG, "onNext: eeeeeeeee"+e.getMessage());
}
});
}
This is so far the easiest method i have ever tried for "Basic Authentication".
Use the below code to generate the auth header (API/Repository class), You can add any character set for encoding as the third parameter here.
var basic = Credentials.basic("YOUR_USERNAME", "YOUR_PASSWORD")
Pass this as header to the webservice call (API/Repository class)
var retrofitCall = myWebservice.getNewsFeed(basic)
Add the basic header as parameter (Retrofit Webservice interface class)
#GET("newsfeed/daily")
fun getNewsFeed(#Header("Authorization") h1:String):Call<NewsFeedResponse>
Sorry, my code is in Kotlin, but can be easily translated to Java.
References: https://mobikul.com/basic-authentication-retrofit-android/

Unexpected character encountered while parsing value: �. Path '', line 0, position 0.

this opportunity Ii'd like to thank everyone who has an answer to this question, I'm trying to get a json from my web api service and I can't this is my code at the web api...
[ResponseType(typeof(List<CompanyType>))]
[Route("GetList")]
[DeflateCompression]
public async Task<IHttpActionResult> Get()
{
List<CompanyType> companyTypes = (List<CompanyType>)MemoryCacheManager.GetValue(#"CompanyTypes");
if (companyTypes != null) return Ok(companyTypes);
companyTypes = await _CompanyType.Queryable().ToListAsync();
if (companyTypes == null) return Ok(HttpStatusCode.NoContent);
MemoryCacheManager.Add(#"CompanyTypes", companyTypes);
return Ok(companyTypes);
}
and at the site of my client I got this
public async Task<T> GetAsync<T>(string action, string authToken = null)
{
using (var client = new HttpClient())
{
if (!authToken.IsNullOrWhiteSpace())
client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse(#"Bearer " + authToken);
var result = await client.GetAsync(BuildActionUri(action));
string json = await result.Content.ReadAsStringAsync();
if (result.IsSuccessStatusCode)
return JsonConvert.DeserializeObject<T>(json); //This line fails because the characters in the value
throw new ApiException(result.StatusCode, json);
}
}
As you can see there nothing than weird here it is a simple code that try to parse a json value to a Generic class but this fails bacause when i call my webapi Url it gives me this value
json = ��VR�LQ�R2T�Q�2u�B*R�"E�e�)�#q�������̔Ԣb%��Ҝ�Z�>#�>#�>�̊B������J�r2�q�
I don't know why my webapi give me tha value, when I try to debug just my service it give me this value
<ArrayOfCompanyType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" ><CompanyType z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/"><Id>1</Id><Type>Privada</Type><JobProviders i:nil="true" /></CompanyType><CompanyType z:Id="i2" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/"><Id>2</Id><Type>Mixta</Type><JobProviders i:nil="true" /></CompanyType><CompanyType z:Id="i3" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/"><Id>3</Id><Type>Publica</Type><JobProviders i:nil="true" /></CompanyType></ArrayOfCompanyType>
as you can see everything looks fine but the problem start when I try to parse to get this value from my client.
this is my class
[DataContract(IsReference = true, Name = #"CompanyType", )]
public class CompanyType : Entity
{
[DataMember(Order = 0)]
public int Id { get; set; }
[DataMember(Order = 1)]
public string Type { get; set; }
[DataMember(Order = 2)]
public virtual List<JobProvider> JobProviders { get; set; }
}
I tried it without de DataContracts and still the same error.
best regards!.
Well I figured out, I was trying to use this sample http://blog.developers.ba/asp-net-web-api-gzip-compression-actionfilter/ but the thing was that the serializer wasn´t registered, so at my startup project I did this
GlobalConfiguration.Configuration.Formatters.Add(new ProtoBufFormatter());
And I changed my Actions deleting the attribute [DeflateCompression]
[ResponseType(typeof(List<CompanyType>))]
[Route("GetList")]
//[DeflateCompression]
public async Task<IHttpActionResult> Get()
{
Logic goes here....
}
And It's working now, but now I have another Issue and its when I try to make a call to my webapi action where I have to response an IHttpActionResult there is an exception of
no serializer defined for type: System.Object

Resources