This is my end point :
#POST("v4/MyStore/data")
Observable<Headers> requestStore(#Body MyStoreRequest request);
I am trying to get response like this :
requestService.requestStore(request)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.map(headers -> {
Log.d("Response",""+headers);
return headers;
}).subscribe(headers -> {
Log.d("Response",""+headers);
},
error -> {
Log.d("ERRRROOOR","Error");
});
I am getting error like below:
Exception: retrofit2.adapter.rxjava.HttpException: HTTP 403 Forbidden
While in postman I am getting response:
Connection →keep-alive
Content-Length →0
Content-Type →application/json; charset=utf-8
Date →Mon, 03 Sep 2018 18:47:30 GMT
MYid →f028df50-c8c5-4cce-92e7-70130345ba46
What I am doing wrong here?
You have to use a Response as your response model because your api is entering error stream in with a code 403
#POST("v4/MyStore/data")
Observable<Response<Void>> requestStore(#Body MyStoreRequest request);
now when you consume response
requestService.requestStore(request)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.map(response -> {
Log.d("Response",""+response);
return response.header();
}).subscribe(headers -> {
Log.d("Response",""+headers);
},
error -> {
Log.d("ERRRROOOR","Error");
});
response.header() will return you the header you want even when your api fails
Probably you're missing headers in your API request from Android client. As per your comment, you're sending bearer token in Authorization headers.
So, you need to send bearer token along with request body like below
#Headers({
"Authorization: Bearer <your_bearer_token_here>", /* change token here */
"Content-Type: application/json"
})
#POST("v4/MyStore/data")
Observable<Headers> requestStore(#Body MyStoreRequest request);
Example,
#Headers({
"Authorization: Bearer ca0df98d-978c-410b-96ec-4e592a788c18",
"Content-Type: application/json"
})
#POST("v4/MyStore/data")
Observable<Headers> requestStore(#Body MyStoreRequest request);
Related
I'm trying to make a simple GET request to our backend server. The request is made successfully and I get status code 200 but one of the attributes (an ArrayList) has no data in the response.
This is particularly strange since the same request returns data in Postman.
I know that the request is going through since I get response code 200.
I don't know what the issue is. Following are the things I have verified are correct.
Base URL is correct
Verified the GET request URL.
Bearer Auth Token is Fine.
Headers (Content-Type & Application) are specified
Retrofit Interface
#Headers("Content-Type: application/json", "Accept: application/json")
#GET("recipe/payment")
fun getMyPurchasedRecipes(
#Header("Authorization") authToken: String
): Call<PurchasedRecipesResponse>
Response Object Data Class
data class PurchasedRecipesResponse(
val code : Int,
val status : String,
#SerializedName("recipes") val recipes : List<Recipes>
)
This is the JSON response in PostMan
{
"code": 200,
"status": "success",
"recipes": [
{
"id": 33,
"title": "Pig tails and Green bananas",
"image_url": "http://api.yardiesfood.com/storage/75/medialibrarykYpREV"
},
{
"id": 32,
"title": "Cheese Omelete",
"image_url": "http://api.yardiesfood.com/storage/68/medialibrarylkjAjm"
}
]
}
In my android app I'm getting the code & status but recipes (from JSON response) returns empty.
Somethings that I have tried
Added headers to the interface #Headers("Content-Type: application/json", "Accept: application/json")
Added #SerializedName to ensure that the JSON to Kotlin class mapping was not the issue.
I am facing a problem with coding my first Android-App.
I want to build the login-system of the app around my existing webserver/webinterface.
I am using the Fuel-Library, and as far as I can tell, the GET Requests are working fine.
The problem is the response. When I print it out, everything is see is some information about the request itself, but the printed echo from PHP isn't showing up anywhere.
Response printed out:
I/System.out: <-- 200 https://...hidden :)
I/System.out: Response : OK
Length : -1
Body : test
Headers : (11)
Connection : Keep-Alive
Date : Mon, 30 Mar 2020 18:06:39 GMT
X-Android-Selected-Protocol : http/1.1
Server : Apache
X-Powered-By : PHP/7.3.5, PleskLin
Content-Type : text/html; charset=UTF-8
X-Android-Received-Millis : 1585591597000
Vary : Accept-Encoding
X-Android-Response-Source : NETWORK 200
X-Android-Sent-Millis : 1585591596960
Keep-Alive : timeout=5, max=100
The same is happening with POST Requests.
Here is my Kotlin-Code:
val url = "https://myserver.com/testlogin.php?username=".plus(username.toString()).plus("&password=").plus(password.toString())
url.httpGet().responseString{
request, response, result ->
Toast.makeText(this#MainActivity, result.toString(), Toast.LENGTH_LONG).show()
}
And the PHP Code on the Webserver:
<?php $username = $_GET["username"]; $password = $_GET["password"]; echo $username; ?>
I am searching for more than 7 hours now. send help
Try this
url.httpGet().responseString { request, response, result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
println(ex)
}
is Result.Success -> {
val data = result.get()
println(data)
}
}
}
Official documentation
I just found the problem:
val data = result.get() println(data)
prints the response string of the php file.
this is the code.
Future<http.Response> postRequest () async {
var url ='http://10.0.2.2:3000/api/message';
Map data = {
'message': '12345678901234567890'
};
//encode Map to JSON
var body = json.encode(data);
var response = await http.post(url,
headers: { "accept": "application/json", "content-type": "application/json" },
body: body
);
print("${response.statusCode}");
print("${response.body}");
return response;
}
postRequest();
// also tried this: headers: {"content-type":"application/json" },
In my python flask server, the post message is logging, but with empty body into it.
The flutter app is running on Android Virtual Device and the server is still running on http://0:0:0:0:3000/ and it's using request.get_json() in the method.
Using postman, everything works as expected on my server so I see the problem in the app.
postman details:
POST: http://localhost:3000/api/message
headers
KEY | VALUE
Content-Type | application/json
Body raw
{
"message": "opa"
}
also raised here: https://github.com/flutter/flutter/issues/39351
Try passing :
Future<http.Response> postRequest () async {
var url ='http://10.0.2.2:3000/api/message';
Map<String, String> data = { "message": "opa" };
var body = json.encode(data);
var response = await http.post(url,
headers: { "accept": "application/json", "content-type": "application/json" },
body: body
);
print(response.statusCode);
print(response.body);
return response;
}
postRequest().then((response){
print(response.body);
});
not sure if my finding is precious or not for community, but it seems that the URL was the problem. Everything works now, but I added a / in the end of the string in my flask app.
In Postman, I didn't have to do this. So if you have same problem, take care :)
The log from Flask server:
127.0.0.1 - - [30/Aug/2019 17:41:32] "POST /api/message/ HTTP/1.1" 200 -
opa
My Flask url is:
#app.route('/api/message/', methods=['POST'])
def function():
I have this simple code to connect to my host:
URL url = new URL("https://www.example.com/getResource");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
m_HttpsConnection.setDoOutput(true);
OutputStream os = m_HttpsConnection.getOutputStream();
DataOutputStream wr = new DataOutputStream(os);
wr.writeBytes("{\"key\":\"value\"}");
wr.flush();
wr.close();
Log.d("MyActivity", "http raw data: " + conn.toString()); <-- this is what I want to achieve!
What I want to see in my logs is the actual HTTP packets that I send to the host like so:
POST /getResource/ HTTP/1.1
Content-Type: application/json
Cache-control: no-cache
Content-Length: 15
{"key":"value"}
How do I do this? Thanks!
For both OkHttpClient and HttpsURLConnection, there is no way to check the complete raw request HTTP packet that you send to a host.
For OkHttpClient, this is the best you can do to check the headers:
class LoggingInterceptor implements Interceptor {
#NotNull
#Override
public Response intercept(#NotNull Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
logger.info(String.format("Sending request %s",
request.headers().toString()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
logger.info(String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
Please take note that when you did not set any header (Request.Builder.header()), nothing will show in your logs. The same observation holds true for HttpsURLConnection. The HttpsURLConnection.getRequestProperties() will only show what you have set in HttpsConnection.setRequestProperty().
For HTTP response, it is a different story. You can get the entire raw response headers.
For HttpsURLConnection you can use below code:
Map<String, List<String>> map = httpsURLConnection.getHeaderFields();
Set<String> keys = map.keySet();
Log.d(TAG, "https response headers: ");
for (String key : keys) {
List<String> list = map.get(key);
for (String value : list) {
Log.d(TAG, "key: " + key + ", value: " + value);
}
}
This gives you everything in your response packet including the HTTP/1.1 200 OK field:
D/MyActivity: key: null, value: HTTP/1.1 200 OK
D/MyActivity: key: Cache-Control, value: private
D/MyActivity: key: Content-Length, value: 20
D/MyActivity: key: Content-Type, value: application/json
D/MyActivity: key: Date, value: Thu, 22 Aug 2019 09:16:06 GMT
D/MyActivity: key: Server, value: Microsoft-IIS/10.0
I believe you can also get the complete response packet for OkHttpClient. I did not check.
My application does post request to url:
https://myserver.domain.com/authenticate/credentials
OkHttp client interceptor shows my headers:
11-17 10:10:56.780 3140-3304/com.myapp.debug D/OkHttp: Content-Type:
application/x-www-form-urlencoded
11-17 10:10:56.780 3140-3304/com.myapp.debug D/OkHttp: Content-Length:
187
11-17 10:10:56.781 3140-3304/com.myapp.debug D/OkHttp: Authorization:
Basic authorisationkeyfortest5430593045903495034905==
11-17 10:10:56.781 3140-3304/com.myapp.debug D/OkHttp:
email=testlogin%40gmail.com&password=test%4012&deviceId=1484564155&deviceLabel=Android%20SDK%20built%20for%20x86_64&deviceType=ANDROID&deviceVersion=23%20%28REL%29
I have created standalone WireMock server and I want redirect every POST request from my APP to my WireMock server. Thats why I have added *.JSON with request definition:
{
"request": {
"method": "POST",
"urlPattern": ".*"
},
"response": {
"proxyBaseUrl" : "https://myserver.domain.com/",
"additionalProxyRequestHeaders": {
"Authorization": "Basic authorisationkeyfortest5430593045903495034905== "
}
}
}
What I expect that should happen:
When I change basepath of my Http client from https://myserver.domain.com/ to http://myserveraddress.com/ - then every request from my app should go to my MockServer. And MockServer according to JSON above should proxy/forward that request to https://myserver.domain.com/ and return the same response - so everything should work fine.
What happens:
Each POST request returns status 200 but body is empty. (it should return authenticated user object)
Question: Is it possible to achieve that? Am I doing something wrong?
Try to add your body in "__files" folder and set path in "bodyFileName"
{
"request": {
"method": "POST",
"urlPattern": ".*"
},
"response": {
"proxyBaseUrl" : "https://myserver.domain.com/",
"additionalProxyRequestHeaders": {
"Authorization": "Basic authorisationkeyfortest5430593045903495034905== "
},
"bodyFileName":".*.json"
}
In JSON file put your answer. For example:
{
"errorCode": 0,
"errorMessage": "",
"result":
{
"filed1":"value",
"filed2":"value"
}
}