Okhttp image file is an empty array - php

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();

Related

Send Body as raw using Guzzle

I am trying to use Guzzle to send POST request to my web service. this service accepts body as raw. It works fine when I use postman but I doesn't using Guzzle. when using Guzzle, I get only the webservice description as I put the web service URL in the browser.
here is my code:
$body = "CA::Read:PackageItems (CustomerId='xxxxxx',AllPackages=TRUE);";
$headers = [
....
....
];
$client = new Client();
$response = $client->request('POST', 'http://172.19.34.67:9882/TisService',$headers,$body);
echo $body = $response->getBody();
seems headers or body doesn't pass through.
Try like this
$response = $client->request('POST', 'http://172.19.34.67:9882/TisService',['headers' => $headers, 'body' => $body]);
I have recently had to implement Guzzle for the first time and it is a fairly simple library to use.
First I created a new Client
// Passed in our options with just our base_uri in
$client = new Client(["base_uri" => "http://example.com"]);
I then created a POST request, not how I am using new Request instead of $client->request(... though. This doesn't really matter to much that I've used new Request though.
// Create a simple request object of type 'POST' with our remaining URI
// our headers and the body of our request.
$request = new Request('POST', '/api/v1/user/', $this->_headers, $this->body);
so in essence it would look like:
$request = new Request('POST', '/api/v1/user/', ['Content-Type' => "application/json, 'Accept' => "application/json"], '{"username": "myuser"}');
$this->headers is a simple key-value pair array of our request headers making sure to set the Content-Type header and $this->body is a simple string object, in my case it forms a JSON body.
I can simply then just call the $client->send(... method to send the request like:
// send would return us our ResponseInterface object as long as an exception wasn't thrown.
$rawResponse = $client->send($request, $this->_options);
$this->_options is a simple key-value pair array again simple to the headers array but this includes things like timeout for the request.
For me I have created a simple Factory object called HttpClient that constructs the whole Guzzle request for me this is why I just create a new Request object instead of calling $client->request(... which will also send the request.
What you essentially need to do to send data as raw is to json_encode an array of your $data and send it in the request body.
$request = new Request(
'POST',
$url,
['Content-Type' => 'application/json', 'Accept' => 'application/json'],
\GuzzleHttp\json_encode($data)
);
$response = $client->send($request);
$content = $response->getBody()->getContents();
Using guzzle Request GuzzleHttp\Psr7\Request; and Client GuzzleHttp\Client

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.

Retrofit does not send header

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

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());

WSDL/Soap web service response complex array parsing using KSOAP2 library

I have created PHP web service using nusoap
$namespace="http:/mynamespace.com/mynamespace"
$server = new soap_server();
$server->debug_flag = false;
$server->configureWSDL("test", $namespace);
$server->wsdl->schemaTargetNamespace = $namespace;
$server->wsdl->addComplexType(
'Products',
'complexType',
'struct',
'all',
'',
array('ID' => array('name' => 'ID','type' => 'xsd:int'),
'ProductName' => array('name' => 'ProductName','type' => 'xsd:string'),
'ImageUrl' => array('name' => 'ImageUrl','type' => 'xsd:string')
)
);
$server->wsdl->addComplexType(
'ProductsArray',
'complexType',
'array',
'',
'SOAP-ENC:Array',
array(),
array(
array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'tns:Products[]')
),
'tns:Products'
);
$server->register('GetProductDetails', // method name
array('AgentId' => 'xsd:string'), // input parameters
array('return' => 'tns:ProductsArray'), // output parameters
$namespace, // namespace
$namespace . '#GetProductDetails', // soapaction
'rpc', // style
'sequence', // use
'Get Product Details' // documentation
);
function GetProductDetails($AgentId)
{
$productArray = array();
$sqlQry="SELECT pr.products_id, pr.products_image, pd.products_name FROM `products` pr left join products_description pd on pr.products_id=pd.products_id";
$result=mysql_query($sqlQry);
while($row=mysql_fetch_array($result)){
$product=array();
$product["ID"]=$row['products_id'];
$product["ProductName"]=$row['products_name'];
$product["ImageUrl"]=$row['products_image'];
$productArray[]=$product;
}
return $productArray;
}
$HTTP_RAW_POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA'])?$GLOBALS['HTTP_RAW_POST_DATA'] : '';
$server->service($HTTP_RAW_POST_DATA);
and I am getting response in android something like
[Products{ID=29; Name=product1; Url=product1.jpg; }, Products{ID=30; Name=product2; Url=product2.jpg; }]
this responce is in one element of response.getProperty(0)
and if I paste this code in http://jsonviewer.stack.hu/ site then it tells me it is not valid json, I am new in nusoap so I don't know how this gives json/XML response
Is there any problem with code?
I have also tried
Android Code:
SoapObject response = (SoapObject) envelope.bodyIn;
SoapObject nameResult = (SoapObject) response.getProperty(0);
In above nameResult I am getting all response in one single property.
I have never used nusoap before but from what I can tell your properly connecting to your db, and according to what i found nusoap can run standard php scripts in which case replaces function GetProductDetails with what i have below (I'm using json_encode), Your problem was with how you load a single result inside the while loop you must use array_push() instead.
function GetProductDetails($AgentId)
{
// array for JSON response
$productArray = array();
$sqlQry="SELECT pr.products_id, pr.products_image, pd.products_name FROM `products` pr left join products_description pd on pr.products_id=pd.products_id";
$result=mysql_query($sqlQry);
while ($row = mysql_fetch_array($result)) {
// temp user array
$product=array();
$product["ID"]=$row['products_id'];
$product["ProductName"]=$row['products_name'];
$product["ImageUrl"]=$row['products_image'];
// push single product into final response array
array_push($poductArray["products"], $product);
}
// echoing JSON response
echo json_encode($productArray);
}
Hope this works it's clearly untested as I dont have your sql (but it's copied from similar script on my server and rewritten for your purposes) also you should cover the case your database is empty
I have solved it by my self, this is help here if any one needs how to solve this..
I am getting response is parsed using Vector and after that I just simply make a loop that get every attribute and add to ArrayList<HashMap<String, String>>.
My process is like, get response from webservice and parsing that response using vector and I just retrieve properties and add to ArrayList<HashMap<String, String>>.
So If here anyone wants to parse complexType Array Response and finds problem like me, they can find solution like following code
public static final ArrayList<HashMap<String, String>> productMapArray = new ArrayList<HashMap<String, String>>();
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
request.addProperty("user_id", "1");
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
Vector<SoapObject> response = (Vector<SoapObject>)envelope.getResponse();
for (SoapObject soapObject : response) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, soapObject.getProperty(KEY_ID).toString());
map.put(KEY_PRODUCT, soapObject.getProperty(KEY_PRODUCT).toString());
map.put(KEY_IMG, soapObject.getProperty(KEY_IMG).toString());
productMapArray.add(map);
}
if (response.toString().equalsIgnoreCase("invalid")) {
result = false;
} else {
result = true;
}
} catch (SocketException ex) {
result = false;
Log.e("Error : ", "Error on soapPrimitiveData() " + ex.getMessage());
ex.printStackTrace();
} catch (Exception e) {
result = false;
Log.e("Error : ", "Error on soapPrimitiveData() " + e.getMessage());
e.printStackTrace();
}
return result;

Categories