Unable to set Test.APIKeyAuthToken - java

This is my code:
public static final String API_TOKEN = "safasfasdfesareasdadasd";
public static final String APIKeyAuthToken = "Auth-Token";
But the Auth-Token is not being found in the header request.
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json");
requestBuilder.addHeader(Test.APIKeyAuthToken, Test.API_TOKEN);
Request request = requestBuilder.build();
return chain.proceed(request);
}

Despite it is rather unclear which API you are even talking about - and what you might mean with "not working" (this is not an error description at all) ...the HTTP header probably should look alike:
.addHeader("Authorization", API_TOKEN)
Just see the API documentation, which string-format is actually being expected... because "not working" might possibly mean, just sending some random header, which the API doesn't accept.

Related

Okhttp3: Need help to use HeaderInterceptor

I would like to use a global header for all my requests. Therefore I have implemented the following class:
public class HeaderInterceptor {
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.method("GET", null)
.addHeader("Accept", "application/json")
.addHeader("Basic ", "abcdefghi123456789")
.build();
Response response = chain.proceed(request);
return response;
}
}
Now I would like to do the following in the main()-method:
public static void main(String[] args) throws Exception {
OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(MyInterceptor).build();
Request reqAllProjects = new Request.Builder()
.url("https://example.com/projects")
.build();
Response resAllProjects = httpClient.newCall(reqAllProjects).execute();
String responseData = resAllProjects.body().string();
System.out.println(responseData);
}
I'm not sure now how to use my HeaderInterceptor. I guess I'll have to enter it here, right?
OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(??MyInterceptor??).build();
I tried something like this: addInterceptor(HeaderInterceptor.intercept()) but this is not working...
Can someone help me please? And does the rest of it look fine? Many thanks in advance!
The interceptor class that you have created doesn't seem to be implementing the Interceptor interface. You need to implement as below
public class HeaderInterceptor implements Interceptor {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Basic ", "abcdefghi123456789")
.build();
Response response = chain.proceed(request);
return response;
}
}
Do note that you should not be modifying the method and body of the request as .method("GET", null) unless you actually need so, as it can result in all the HTTP requests made by the client to make GET requests with null body.
Then add the interceptor while building the client as below
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new HeaderInterceptor()).build();
Have a look at the OkHttp documentation for more info.
Have you checked this question : Okhttp3: Add global header to all requests error
It should be something like
.addInterceptor(new Interceptor())

RestController - Forward POST request to external URL

I'm looking for a way how to forward POST request which has been made to endpoint in #RestController class and forward it to external URL with body and headers untouched (and return response from this API of course), is it possible to do it by using some spring features? The only solution which I have found is extracting a body from #RequestBody and headers from HttpServletRequest and use RestTemplate to perform a request. Is there any easier way?
#RequestMapping("/**")
public ResponseEntity mirrorRest(#RequestBody(required = false) String body,
HttpMethod method, HttpServletRequest request, HttpServletResponse response)
throws URISyntaxException {
String requestUrl = request.getRequestURI();
URI uri = new URI("http", null, server, port, null, null, null);
uri = UriComponentsBuilder.fromUri(uri)
.path(requestUrl)
.query(request.getQueryString())
.build(true).toUri();
HttpHeaders headers = new HttpHeaders();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
headers.set(headerName, request.getHeader(headerName));
}
HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);
RestTemplate restTemplate = new RestTemplate();
try {
return restTemplate.exchange(uri, method, httpEntity, String.class);
} catch(HttpStatusCodeException e) {
return ResponseEntity.status(e.getRawStatusCode())
.headers(e.getResponseHeaders())
.body(e.getResponseBodyAsString());
}
}
The above code is taken from this answer.
This is more a matter of the HTTP spec than Spring where the server would be expected to return a 307 redirect status, indicating the client should follow the redirect using the same method and post data.
This is generally avoided in the wild as there's a lot of potential for misuse, and friction if you align with the W3.org spec that states the client should be prompted before re-executing the request at the new location.
One alternative is to have your Spring endpoint act as a proxy instead, making the POST call to the target location instead of issuing any form of redirect.
307 Temporary Redirect (since HTTP/1.1) In this occasion, the request should be repeated with another URI, but future requests can still use the original URI.2 In contrast to 303, the request method should not be changed when reissuing the original request. For instance, a POST request must be repeated using another POST request.

how java unirest to set content-length

java.
I use Unirest.post to post my multipart data. but server shows error to me:
multipart: NextPart: EOF.
I find that, if I set Content-Length I can solve this.
Here the code:
String buff = "my data";
HttpResponse<String> res = Unirest.post(url)
.header("Content-Type", multipart.getContentType().getValue())
.header("Content-Length", String.valueOf(buff.length()))
.body(buff).asString();
But after I add .header("Content-Length", String.valueOf(buff.length())), run java I get error:
org.apache.http.client.ClientProtocolException
How can I solve this?
You need to remove the earlier set content length so that you can set a new one.
#John Rix's answer This code helped solved the problem
private static class ContentLengthHeaderRemover implements HttpRequestInterceptor{
#Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
request.removeHeaders(HTTP.CONTENT_LEN);// fighting org.apache.http.protocol.RequestContent's ProtocolException("Content-Length header already present");
}
}
HttpClient client = HttpClients.custom()
.addInterceptorFirst(new ContentLengthHeaderRemover())
.build();

How to change response body in intercept (Using retrofit 2)

I read thousand of answers and try to a lot of way but doesn't work.
I really need to change response body when get "401". Because server response is different from other general response when unauthorized.
I'm using retrofit 2. To catch response i'm using Interceptor:
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("authorization", getAccessToken(context));
Request request = requestBuilder.build();
Response response= chain.proceed(request);
if (response.code()==401) {
MediaType contentType = response.body().contentType();
ResponseBody body = ResponseBody.create(contentType, CommonFunctions.getUnAuthorizedJson(context).toString());
return response.newBuilder().body(body).build();
}else{
return response;
}
But still body doesn't change on client.enque method.
You can change body in this way, but Retrofit will eventually see 401 and throw HttpException with standart message, what can be misleading
check that you get your body right:
val errorConverter: Converter<ResponseBody, ErrorResponse> =
retrofit.responseBodyConverter(
ErrorResponse::class.java,
emptyArray()
)
val errorResponse = httpException
.response()
?.errorBody()
?.let (errorConverter::convert)

Content type : "Application/Json" issue with retrofit 2.2 while calling cake php apis

My Api is accepting Content-Type application/json as headers. I set Header perfectly as mentioned in Retrofit Docs.
#Headers("Content-Type: application/json")
#POST("user/classes")
Call<playlist> addToPlaylist(#Body PlaylistParm parm);
I also tried by setting content type in authentication interceptor class:
public class AuthenticationInterceptor implements Interceptor {
private String authToken;
public AuthenticationInterceptor(String token) {
this.authToken = token;
}
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder()
.addHeader("Content-type","application/json")
.addHeader("Authorization", authToken);
Request request = builder.build();
return chain.proceed(request);
}
}
But in Request Log it is Returning Content-Type txt/html.So how i should fix this issue? This api works fine in POSTMAN
I tried with all possible ways but it's not working with cake php web services.
Any help would be appreciated.

Categories