Titanium : TiHttpClient error on host connecting - android

Description: I want to connect to server via POST request. My method, which posts the request:
function loginClick(e) {
var url = "http://...";
var xhr = Ti.Network.createHTTPClient({
onload: function (e) { // this function is called when data is returned from the server and available for use
// this.responseText holds the raw text return of the message (used for text/JSON)
// this.responseXML holds any returned XML (including SOAP)
// this.responseData holds any returned binary data
Ti.API.debug(this.responseText);
alert(xhr.responseText);
},
onerror: function (e) { // this function is called when an error occurs, including a timeout
Ti.API.debug(e.error);
alert(e.toString);
},
timeout: 5000 /* in milliseconds */
});
xhr.autoEncodeUrl = false;
var params = {
email: $.email.value,
password: $.password.value
};
xhr.open('POST', url);
xhr.send(params); // request is actually sent with this statement
Ti.API.info(xhr.responseText);
};
But I can't do it because receive strange message. I put it in the Logs. Besides, I did another requests and they worked successfully.
Logs:
[ERROR] : TiHttpClient: (TiHttpClient-1) [3529,3529] HTTP Error (org.apache.http.client.HttpResponseException): Not Found
[ERROR] : TiHttpClient: org.apache.http.client.HttpResponseException: Not Found
[ERROR] : TiHttpClient: at ti.modules.titanium.network.TiHTTPClient$LocalResponseHandler.handleResponse(TiHTTPClient.java:258)
[ERROR] : TiHttpClient: at ti.modules.titanium.network.TiHTTPClient$LocalResponseHandler.handleResponse(TiHTTPClient.java:217)
[ERROR] : TiHttpClient: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657)
[ERROR] : TiHttpClient: at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:637)
[ERROR] : TiHttpClient: at ti.modules.titanium.network.TiHTTPClient$ClientRunnable.run(TiHTTPClient.java:1287)
[ERROR] : TiHttpClient: at java.lang.Thread.run(Thread.java:841)

I solved it with JSON.stringify(params) with the sending the request :
function loginClick(e)
{
var url = 'http://...';
var xhr = Ti.Network.createHTTPClient({
onload: function(e) {
// this function is called when data is returned from the server and available for use
// this.responseText holds the raw text return of the message (used for text/JSON)
// this.responseXML holds any returned XML (including SOAP)
// this.responseData holds any returned binary data
Ti.API.debug(this.responseText);
alert(xhr.responseText);
},
onerror: function(e) {
// this function is called when an error occurs, including a timeout
Ti.API.debug(e.error);
alert(this.status);
alert("error" + e.toString);
},
timeout:5000 /* in milliseconds */
});
xhr.autoEncodeUrl = false;
var params = {
'email': $.email.value,
'password' :$.password.value
};
xhr.open('POST', url);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.send(JSON.stringify(params)); // request is actually sent with this statement
};

The "Not Found" exception makes sense. I tried doing a POST with CURL to demonstrate that this isn't caused by Titanium. Your URL is wrong.
> curl --verbose --data "email=test#mail.com&password=dnipro" http://www.assignmentexpert.com/api/v1
* Adding handle: conn: 0x7ffdc4004400
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7ffdc4004400) send_pipe: 1, recv_pipe: 0
* About to connect() to www.assignmentexpert.com port 80 (#0)
* Trying 198.72.112.182...
* Connected to www.assignmentexpert.com (198.72.112.182) port 80 (#0)
> POST /api/v1 HTTP/1.1
> User-Agent: curl/7.30.0
> Host: www.assignmentexpert.com
> Accept: */*
> Content-Length: 35
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 35 out of 35 bytes
< HTTP/1.1 404 Not Found
* Server nginx/1.4.7 is not blacklisted
< Server: nginx/1.4.7
< Date: Fri, 25 Apr 2014 16:45:58 GMT
< Content-Type: text/html; charset=utf-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< X-Powered-By: PHP/5.4.26
< Set-Cookie: updater=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22d0a5527549f76365252a61361cd78e59%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A12%3A%2298.218.93.45%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A11%3A%22curl%2F7.30.0%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1398444358%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D7b00051302d9b00cd28b355be89a1e98; expires=Sun, 24-Apr-2016 16:45:58 GMT; path=/
< Set-Cookie: logged=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT
< Location: /api/v1/
<
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
(truncated -- HTML returned is identical to www.assignmentexpert.com)

Related

How to get this iOS Http Post Request to work?

I am setting up a payout process for a driver in my app with Firebase Cloud Functions and Paypal. The url to be posted is the url of the actual cloud function in Firebase:
https://us-central1-ryyde-sj.cloudfunctions.net/payout
When trying to send an HTTP Post Request, it doesn't seem to be working. See the payoutRequest() and the Response code below:
payoutRequest()
let email = txtPayoutEmail.text!
let uid = self.uid!
// Prepare URL:
let url = URL(string: "https://us-central1-ryyde-sj.cloudfunctions.net/payout")
guard let requestUrl = url else { fatalError() }
// Prepare URL Request Object:
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
// Set HTTP Request Headers
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Your Token", forHTTPHeaderField: "Authorization")
request.setValue("no-cache", forHTTPHeaderField: "cache-control")
print("request = \(request)")
// HTTP Request Parameters which will be sent in HTTP Request Body:
let postString = "uid=\(uid)&email=\(email)"
print("postString = \(postString)")
// Set HTTP Request Body
request.httpBody = postString.data(using: String.Encoding.utf8)
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error ) in
print("data: \(String(describing: data))")
print("response: \(String(describing: response))")
print("error: \(String(describing: error))")
if let response = response as? HTTPURLResponse {
// Read all HTTP Response Headers
print("All headers: \(response.allHeaderFields)")
// Read a specific HTTP Response Header by name
if #available(iOS 13.0, *) {
print("Specific header: \(response.value(forHTTPHeaderField: "Content-Type") ?? " header not found")")
} else {
// Fallback on earlier versions
}
}
// Check for Errors
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string: \(dataString)")
}
}
task.resume()
Response
request = https://us-central1-ryyde-sj.cloudfunctions.net/payout
postString = uid=kv8JRVBwAfS1tgD04lNeM9esVzI2&email=myiosapp#me.com
data: Optional(138 bytes)
response: Optional(<NSHTTPURLResponse: 0x6000037d1c20> { URL: https://us-central1-ryyde-sj.cloudfunctions.net/payout } { Status Code: 400, Headers {
"Content-Length" = (
138
);
"Content-Type" = (
"text/html; charset=utf-8"
);
Date = (
"Thu, 17 Sep 2020 01:00:50 GMT"
);
Server = (
"Google Frontend"
);
"alt-svc" = (
"h3-Q050=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000,h3-27=\":443\"; ma=2592000,h3-T051=\":443\"; ma=2592000,h3-T050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\""
);
"content-security-policy" = (
"default-src 'none'"
);
"function-execution-id" = (
cmrwbktlroxl
);
"x-cloud-trace-context" = (
"a85aaacd578e60690581aa64ead13b23;o=1"
);
"x-content-type-options" = (
nosniff
);
"x-powered-by" = (
Express
);
} })
error: nil
All headers: [AnyHashable("content-security-policy"): default-src 'none',
AnyHashable("Date"): Thu, 17 Sep 2020 01:00:50 GMT, AnyHashable("alt-svc"): h3-Q050=":443";
ma=2592000,h3-29=":443"; ma=2592000,h3-27=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-
T050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443";
ma=2592000; v="46,43", AnyHashable("Content-Type"): text/html; charset=utf-8,
AnyHashable("Content-Length"): 138, AnyHashable("x-cloud-trace-context"):
a85aaacd578e60690581aa64ead13b23;o=1, AnyHashable("Server"): Google Frontend,
AnyHashable("x-powered-by"): Express, AnyHashable("x-content-type-options"): nosniff,
AnyHashable("function-execution-id"): cmrwbktlroxl]
Specific header: text/html; charset=utf-8
Response data string: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Bad Request</pre>
</body>
</html>
If the request is successful, then it would show up in the PayPal Notifications for PayPal Sandbox at the below link, but it isn't.
PayPal developer notifications link
I don't have much experience in PayPal HTTP requests.
I have done the same thing as I am trying to do here but in Android and it works perfectly so I know this should work, other than the Post Request (I tried using examples online to match what i had for the Android app)
Edit
updated payoutRequest():
Code surrounded in ** ** is new code
let email = txtPayoutEmail.text!
let uid = self.uid!
// Prepare URL:
let url = URL(string: "https://us-central1-ryyde-sj.cloudfunctions.net/payout")
guard let requestUrl = url else { fatalError() }
// Prepare URL Request Object:
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
// Set HTTP Request Headers
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Your Token", forHTTPHeaderField: "Authorization")
request.setValue("no-cache", forHTTPHeaderField: "cache-control")
print("request = \(request)")
// HTTP Request Parameters which will be sent in HTTP Request Body:
**let body = ["uid": uid, "email": email]**
print("body = \(body)")
// Set HTTP Request Body
**request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])**
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error ) in
print("data: \(String(describing: data))")
print("response: \(String(describing: response))")
print("error: \(String(describing: error))")
if let response = response as? HTTPURLResponse {
// Read all HTTP Response Headers
print("All headers: \(response.allHeaderFields)")
// Read a specific HTTP Response Header by name
if #available(iOS 13.0, *) {
print("Specific header: \(response.value(forHTTPHeaderField: "Content-Type") ?? " header not found")")
} else {
// Fallback on earlier versions
}
}
// Check for Errors
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string: \(dataString)")
}
}
task.resume()
Response:
request = https://us-central1-ryyde-sj.cloudfunctions.net/payout
body = ["uid": "kv8JRVBwAfS1tgD04lNeM9esVzI2", "email": "driver#ryyde.com"]
data: Optional(0 bytes)
response: Optional(<NSHTTPURLResponse: 0x600001f0d6a0> { URL: https://us-central1-ryyde-sj.cloudfunctions.net/payout } { Status Code: 200, Headers {
"Content-Length" = (
0
);
"Content-Type" = (
"text/html"
);
Date = (
"Thu, 17 Sep 2020 04:41:29 GMT"
);
Server = (
"Google Frontend"
);
"alt-svc" = (
"h3-29=\":443\"; ma=2592000,h3-27=\":443\"; ma=2592000,h3-T051=\":443\"; ma=2592000,h3-T050=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\""
);
"function-execution-id" = (
cmrwtq89fdsr
);
"x-cloud-trace-context" = (
"f3fe884ca8499e7a10c7081ce222876e;o=1"
);
"x-powered-by" = (
Express
);
} })
error: nil
All headers: [AnyHashable("Content-Length"): 0, AnyHashable("x-cloud-trace-context"): f3fe884ca8499e7a10c7081ce222876e;o=1, AnyHashable("Server"): Google Frontend, AnyHashable("x-powered-by"): Express, AnyHashable("function-execution-id"): cmrwtq89fdsr, AnyHashable("alt-svc"): h3-29=":443"; ma=2592000,h3-27=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43", AnyHashable("Date"): Thu, 17 Sep 2020 04:41:29 GMT, AnyHashable("Content-Type"): text/html]
Specific header: text/html
Response data string:
EDIT 2
When I run my code, I check the function logs in firebase/functions (read from bottom up - seems to go ok with the function activity)
EDIT 3 - Charles Session results
URL https://us-central1-ryyde-sj.cloudfunctions.net Status Sending
request body… Notes Transaction began prior to session being cleared,
body content transmitted before the session clear has not been
captured Response Code 200 Connection established Protocol HTTP/1.1
TLS TLSv1.2 (TLS_AES_128_GCM_SHA256) Protocol TLSv1.2 Session
Resumed Yes Cipher Suite TLS_AES_128_GCM_SHA256 ALPN - Client
Certificates - Server Certificates - Extensions Method CONNECT Kept
Alive No Content-Type Client Address 127.0.0.1:57209 Remote
Address us-central1-ryyde-sj.cloudfunctions.net/216.239.36.54:443
Tags - Connection WebSockets - Timing Size Request 1.77 KB (1,817
bytes) Response 1.35 KB (1,379 bytes)
EDIT 4 - Android code
private void payoutRequest() {
progress = new ProgressDialog(this);
progress.setTitle("Processing your payout ...");
progress.setMessage("Please Wait .....");
progress.setCancelable(false);
progress.show();
// HTTP Request ....
final OkHttpClient client = new OkHttpClient();
// in json - we need variables for the hardcoded uid and Email
JSONObject postData = new JSONObject();
try {
postData.put("uid", FirebaseAuth.getInstance().getCurrentUser().getUid());
postData.put("email", mPayoutEmail.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
// Request body ...
RequestBody body = RequestBody.create(MEDIA_TYPE, postData.toString());
// Build Request ...
final Request request = new Request.Builder()
.url("https://us-central1-ryyde-sj.cloudfunctions.net/payout")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("cache-control", "no-cache")
.addHeader("Authorization", "Your Token")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// something went wrong right off the bat
progress.dismiss();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// response successful ....
// refers to response.status('200') or ('500')
int responseCode = response.code();
if (response.isSuccessful()) {
switch(responseCode) {
case 200:
Snackbar.make(findViewById(R.id.layout),
"Payout Successful!", Snackbar.LENGTH_LONG)
.show();
break;
case 500:
Snackbar.make(findViewById(R.id.layout),
"Error: no payout available", Snackbar
.LENGTH_LONG).show();
break;
default:
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
break;
}
} else {
Snackbar.make(findViewById(R.id.layout),
"Error: couldn't complete the transaction",
Snackbar.LENGTH_LONG).show();
}
progress.dismiss();
}
});
}
try this:
let body = ["uid": uid,
"email": email]
request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])

HTTP GET-Request in Kotlin/Android Studio

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.

Show the actual raw data + HTTPS headers sent by HttpsURLConnection

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.

WireMock proxying not returning any body

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"
}
}

Using #PUT with Retrofit 2 and OkHttp3

Currently, I am using Android with Retrofit 2.0.0-beta4 and OkHttp3. I am doing a #PUT request defined as so:
#Headers({
Constants.CONTENT_TYPE_HEADER + ": " + Constants.JSON_HEADER_VAL,
Constants.ACCEPT_HEADER + ": " + Constants.JSON_HEADER_VAL
})
#PUT(Constants.PUT_SKILL_LEVEL)
Call<EmployeeSkill> updateEmpSkillLevel(#Header(Constants.SESSION_COOKIE_NAME) String cookieValue, #Body EmployeeSkillRequest employeeSkillUpdate);
The endpoint goes here: http://apps:8080/employeeSkillsService/employeeSkill. Here is the log output from the PUT request:
D/OkHttp﹕ --> PUT http://apps:8080/employeeSkillsService/employeeSkill http/1.1
D/OkHttp﹕ Content-Type: application/json;charset=UTF-8
D/OkHttp﹕ Content-Length: 99
D/OkHttp﹕ Accept: application/json
D/OkHttp﹕ JSESSIONID: D147377AB60AFE499D2A1AAF7C93F7A3
D/OkHttp﹕ {"employee":{"id":63},"skill":{"isPrimary":false,"isSecondary":false,"id":3},"skillLevel":{"id":5}}
D/OkHttp﹕ --> END PUT (99-byte body)
<-- 404 Not Found http://apps:8080/employeeSkillsService/app.html (23ms)
D/OkHttp﹕ Server: Apache-Coyote/1.1
D/OkHttp﹕ X-Content-Type-Options: nosniff`D/OkHttp﹕ X-XSS-Protection: 1; mode=block`
D/OkHttp﹕ X-XSS-Protection: 1; mode=block
D/OkHttp﹕ Cache-Control: no-cache, no-store, max-age=0, must-revalidate
D/OkHttp﹕ Pragma: no-cache
D/OkHttp﹕ Expires: 0
D/OkHttp﹕ X-Frame-Options: DENY
D/OkHttp﹕ Content-Type: text/html;charset=utf-8
D/OkHttp﹕ Content-Language: en
D/OkHttp﹕ Content-Length: 1029
D/OkHttp﹕ Date: Mon, 07 Mar 2016 15:39:35 GMT
D/OkHttp﹕ OkHttp-Sent-Millis: 1457365206407
D/OkHttp﹕ OkHttp-Received-Millis: 1457365206412
D/OkHttp﹕ <html><head><title>Apache Tomcat/7.0.52 (Ubuntu) - Error report</title><style><!--H1
{font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2
{font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3
{font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B{font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 404 - /employeeSkillsService/app.html</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>/employeeSkillsService/app.html</u></p><p><b>description</b> <u>The requested resource is not available.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.52 (Ubuntu)</h3></body></html>
D/OkHttp﹕ <-- END HTTP (1029-byte body)
I have verified in Postman on Chrome that this endpoint with these headers and payload works multiple times. Yet when I use Retrofit I keep receiving a 404 error despite the endpoint working in Postman. Here is the code call:
Call<EmployeeSkill> updateEmployeeSkillCall = RetrofitApiRestClient.getApiClient().updateEmpSkillLevel(cookieValue, employeeSkillUpdate);
updateEmployeeSkillCall.enqueue(new Callback<EmployeeSkill>() {
#Override
public void onResponse(Call<EmployeeSkill> call, Response<EmployeeSkill> response) {
// called when response HTTP status is "200 OK"
if (response.isSuccess()) {
holder.spnSkillLevel.setTag(pos);
Toast.makeText(mContext, holder.tvSkillName.getText() + mContext.getString(R.string.skill_updated_success_text)
+ holder.spnSkillLevel.getSelectedItem().toString(), Toast.LENGTH_LONG).show();
List<EmployeeSkill> updateEmployeeSkillsRow = EmployeeSkill.find(EmployeeSkill.class, "employee = ? and skill = ?",
response.body().getEmployee().getId().toString(), response.body().getSkill().getId().toString());
EmployeeSkill updatedSkill = updateEmployeeSkillsRow.get(0);
updatedSkill.setSkillLevel(response.body().getSkillLevel());
updatedSkill.setTimeUpdated(response.body().getSkillLevel().getTimeUpdated());
updatedSkill.save();
}
}
#Override
public void onFailure(Call<EmployeeSkill> call, Throwable throwable) {
Toast.makeText(mContext, holder.tvSkillName.getText() + mContext.getString(R.string.skill_update_failed_text), Toast.LENGTH_LONG).show();
}
});
I have tried changing the #Body parameter to a JSON String, but I received an error that stated that the JSON must begin with an array or object. Any help in this matter would be useful. Without this functionality, I will be forced to scrap Retrofit if I cannot find a solution and I am not really looking forward to doing that.
Solved my own issue using Fiddler2. Had the cookie name and value incorrect. Postman was probably more forgiving in how it sent things vs. how Retrofit and others did so. Learned something from it, though. Thanks to all who assisted.

Categories

Resources