Retrofit does not send header - php

I'm currently working on an Android app and I have a problem, I'm trying to send a header in my request with retrofit but when I check on my server with PHP it looks like the header does not even exists.
Here is my code:
Android
#Headers("SECRET_KEY: QWERTZUIOP")
#GET("{TableName}/")
Call<List<Data>> cl_getAllFromTable(#Path("TableName") String TableName);
PHP Server
$secret_key = $_SERVER['HTTP_SECRET_KEY'];
I'd be glad if someone could help. Thanks in advance.
Teasel

// Define the interceptor, add authentication headers
Interceptor interceptor = new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder().addHeader("User-Agent", "Retrofit-Sample-App").build();
return chain.proceed(newRequest);
}
};
// Add the interceptor to OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(interceptor);
OkHttpClient client = builder.build();
// Set the custom client when building adapter
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
Reference: https://guides.codepath.com/android/Consuming-APIs-with-Retrofit

Related

Okhttp image file is an empty array

I am sending an image and associated data from my Android app to my laravel php backend
final MediaType JPEG = MediaType.parse("image/JPEG; charset=utf-8");
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("filename", image.getFilename())
.addFormDataPart("hash", image.getHash())
.addFormDataPart("job_id", Integer.toString(image.getJobId()))
.addFormDataPart("team", Integer.toString(image.getTeam()))
.addFormDataPart("type", image.getType())
.addFormDataPart("image_file", image.getFilename(), RequestBody.create(JPEG, imagefile)).build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
The backend php looks like this
public function updateJobImage(array $request_data){
var_dump($request_data);
$toInsertImage = [
'job_id' => $request_data['job_id'],
'type' => $request_data['type'],
'filename' => $request_data['filename'],
'team' => $request_data['team'],
'hash' => $request_data['hash']
];
$filepath = '/schedule_images/' . $request_data['hash'] . "/" . $request_data['filename'];
Storage::disk('s3_upload')->put($filepath, file_get_contents($request_data['image_file']));
I can get all the job_id/type/filename/team/hash data perfectly fine but the image_file is an empty array. How do I handle getting the image file on the php side
Please also check that image.getfilename() exist or not
final MediaType MEDIA_TYPE = new image.getfilename().endsWith("jpg") ?
MediaType.parse("image/png") :
MediaType.parse("image/jpeg");
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("image_file", System.currentTimeMillis()+"profile.jpg", RequestBody.create(MEDIA_TYPE, image.getfilename()))
.build();
Request request = new Request.Builder()
.post(requestBody)
.url(url)
.build();

OKHttp put and post requests not working

I'm trying to use OKHttp to send a request to my php backend. I'm using this code:
public static String putRequestWithHeaderAndBody(String url, String header, String jsonBody) throws IOException
{
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jsonBody);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.put(body) //PUT
.addHeader("Authorization", header)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
I then try to read the put body from php using this line of code:
$data = json_decode(file_get_contents("php://input"), true);
However, it always seems to be empty. I feel like I am making a silly mistake, I cannot seem to find out what is wrong though.
The request does return the correct response body when I send it using Postman.

Android / Loopj - How can i POST a complex JSON object to a server?

In one of my application, in which I use the Loopj library, I need to send a complex object to a web-service (running on PHP). I decided to send a JSON object via HTTP POST request using Loppj example.
JSONObject params = new JSONObject();
try
{
params.put("params1", "value1");
params.put("params2", "value2");
params.put("params3", "value3");
}
catch(JSONException e)
{
// ...
}
StringEntity entity = new StringEntity(params.toString(), HTTP.UTF_8);
ArrayList<Header> array = new ArrayList<>();
array.add(new BasicHeader("Content-type", "application/json"));
array.add(new BasicHeader("Accept", "application/json"));
Header[] headers = new Header[headers.size()];
headers = headers.toArray(array);
AsyncHttpClient client = new AsyncHttpClient();
client.post(context, url, headers, entity, "application/json", new JsonHttpResponseHandler()
{
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response)
{
//...
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable e, JSONObject errorResponse)
{
// ...
}
});
Unfortunately, $_POST / $_REQUEST are always empty. I've searched different tips but none of them is working. I haven't restriction on routes in my web-service, just a simple function to dump posted parameters.
EDIT 1
To check posted parameters, I coded a simple PHP page to log them. Thanks to #Steve, I was abble to find them in php://input.
file_put_contents(__DIR__ . '/post_data.log', json_encode($_POST));
file_put_contents(__DIR__ . '/input_data.log', file_get_contents('php://input'));
The fact is that I'm not the owner of the final web-services, so I can't change access to data. They must be accessible through $_POST. So, sending application/json isn't the solution ? How AJAX can send complex objects to a server and find them in $_POST, and not Android ?
EDIT 2
I tried to do the same with PostMan and $_POST is always empty. So, I analyzed the request sent by jQuery.ajax(...) (which allow you to send JSON object) and it generate proper key/value from JSON object.
For example, the JSON object :
{
"users":[
{
"name":"jean",
"age":"25",
"city":"paris"
}
]
}
It is converted in 3 pairs key/value :
users[0][name] : jean
users[0][age] : 25
users[0][city] : paris.
So, I guess I need a function which convert my JSONObject into RequestParams object and send it "normally" through "x-www-form-urlencoded". I don't know if there's any native function which can do this but I found the Javascript equivalent (Query-string encoding of a Javascript Object).
serialize = function(obj, prefix) {
  var str = [], p;
  for(p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push((v !== null && typeof v === "object") ?
        serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
  }
  return str.join("&");
}
As I said previously, I wrote a helper class which convert JSONObject to RequestParams which can "normally" be sent over POST HTTP method.
I copy/paste it and wrote a quick README file. If you have any suggestions or even pull-requests, please share.
Hope it helps.
https://github.com/schnapse/json-to-requestparams

Unable to fetch sessionId for Magento API using SOAP webservice in Android

I am developing an Android mobile app for Magento website, I have created user and set role in admin panel of Magento, but I am unable to fetch the sessionId from it. I am using soap web service and my code is for connecting to the web service is:
private static final String NAMESPACE = "urn:Magento";
private static final String URL = "http://localhost.../index.php/api/index/index/?wsdl";
private static final String MAGENTO_METHOD_NAME = "login";
try {
SoapSerializationEnvelope env = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
SoapObject request = new SoapObject(NAMESPACE, MAGENTO_METHOD_NAME);
request.addProperty("username", "web_service_all");
request.addProperty("apiKey", "WebServiceUser";
env.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call("", env);
Object result = env.getResponse();
value=String.valueOf(so);
Log.d("sessionId", result.toString());
} catch (Exception e) {
e.printStackTrace();

how to send keypair valuie using ksoap2 library in android?

I want to send key-pair values in soap web Service using ksoap2 library in android.
Like :
Map<String,String> map = new Map<String,String>();
map.put(key,value);
map.put(key,value);
Vector<Object> vector = new Vector<Object>();
vector.add(10);
vector.add(map);
Now this vector send in ksoap2 library then its give serialization error.
if another way to send this map in ksoap2 library.
i got the solutiuon ...
Hashtable hashtable = new Hashtable();
hashtable.put("is_report", false);
hashtable.put("r_how", 1);
_client.addProperty("params",hashtable);
SoapSerializationEnvelope _envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
_envelope.bodyOut = _client;
HttpTransportSE _ht = new HttpTransportSE("drebedengi.ru/soap/");
_ht.debug = true;
(new MarshalHashtable()).register(_envelope);
If your using Ksoap2: you can do like this also....
//creating object of soap with parameter name
SoapObject param = new SoapObject(NAMESPACE,"shoppingCartProductEntity");
param.addProperty("product_id","886");
param.addProperty("sku","ABC 456-Black-10");
/* creating array of the product details
SoapObject EntityArray = new SoapObject(NAMESPACE, "shoppingCartProductEntityArray");
EntityArray.addProperty("products",param); */
//normal soap call
SoapObject request = new SoapObject(NAMESPACE,"shoppingCartProductAdd");
request.addProperty("sessionId", sessionId);
request.addProperty("quoteId", cartId);
request.addProperty("products",param (or) EntityArray); //adding array to cart
env.setOutputSoapObject(request);
androidHttpTransport.call(NAMESPACE +"/shoppingCartProductAdd ", env);
resultSoap = env.getResponse();
Log.d("****result****", resultSoap.toString());

Categories