Zend Http Client Reponse header data? - magento

I get json file content using the zend http client in magento.
I don't need header info on getBody(). I did test it on some host where it works. But the live host gives me troubles.
$request_url = "link";
$httpClientConfig = array('maxredirects' => 0);
$client = new Zend_Http_Client($request_url, $httpClientConfig);
$client->setMethod(Zend_Http_Client::GET);
try {
$response = $client->request();
} catch (Exception $e) {
Mage::throwException($this->__('Gateway request error: %s', $e->getMessage()));
}
Mage::log($response->getBody());
Result logging:
2015-01-08T09:12:46+00:00 DEBUG (7): HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 761
Connection: close
Date: Mon, 05 Jan 2015 22:53:40 GMT
Last-Modified: Sat, 15 Nov 2014 10:14:17 GMT
ETag: "a8b17a42b7ef7e5960f9bd325a8c1892"
Accept-Ranges: bytes
Server: AmazonS3
Age: 5574
X-Cache: Hit from cloudfront
Via: 1.1 522dd06c4c8acf822ccbebe21aee8d1c.cloudfront.net (CloudFront)
X-Amz-Cf-Id: c6K9QJnOESg1NERKjG-v2fX_9eskmCzz_KUYdXrOb2NSjVTbWZ_x8Q==
{
"assets": {
"standard": {
"url": "https://d3k1w8lx8mqizo.cloudfront.net/standard.png",
"infobox": {
"page1": "https://d3k1w8lx8mqizo.cloudfront.net/frontside.png",
"page2": "https://d3k1w8lx8mqizo.cloudfront.net/backside.png"
}
},
"promotion": {
"infobox": {
"page1": "https://d3k1w8lx8mqizo.cloudfront.net/frontside.png",
"page2": "https://d3k1w8lx8mqizo.cloudfront.net/backside.png"
},
"url": "https://d3k1w8lx8mqizo.cloudfront.net/standard.png",
"interest_free_months": 6,
"transaction_limit_min": 240.0
}
}
}

Try this:
Zend_Http_Response::extractBody($response->getBody());
Or don't retrieve the headers in the request when instantiating the Zend_Http_Client:
$httpClientConfig = array(
'maxredirects' => 0,
'curloptions' => array(CURLOPT_HEADER => false),
);
If the above doesn't work, you can try an alternative way of doing the request such as file_get_contents:
$response = file_get_contents($request_url);
I hope it helps.

Related

Ambari api POST complaining CSRF protection

I am trying to set hbase property through Ambari API using following command
curl -u "admin:admin" -i -X POST -d '{"type": "hbase-site", "tag": "version3", "properties" : {"hbase.regionserver.global.memstore.size" : "0.6"}}' https://abct.net/api/v1/clusters/xyz/configurations
But keep getting following error
HTTP/1.1 400 Bad Request
Content-Length: 107
Content-Type: text/plain
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Server: Microsoft-IIS/8.5
x-ms-hdi-active: 10.8.18.29
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
User: admin
X-Powered-By: ARR/3.0
Set-Cookie: AMBARISESSIONID=2e8ortl32j1p7zdjatigdgvg;Path=/;HttpOnly; path=/; secure
X-Powered-By: ASP.NET
Date: Mon, 12 Sep 2016 18:19:38 GMT
{
"status" : 400,
"message" : "CSRF protection is turned on. X-Requested-By HTTP header is required."
}
What am missing here ?
Turns out you have to add the request header to the request for anything other than a GET request.
You can add the header with
curl --header "X-Requested-By: my_computer_name"
Or
You can disable this feature.
I had same problem in c# Rest client. Using Brig's answer fixed it:
HttpClientHandler handler = new HttpClientHandler
{
Credentials = new System.Net.NetworkCredential("xxxx", "yyyyy"),
};
using (var httpClient = new HttpClient(handler))
{
//"X-Requested-By: my_computer_name"
httpClient.DefaultRequestHeaders.Add("X-Requested-By","my_computer_name");

File is not being downloaded on Laravel5 using Response

I use Laravel 5.1.
A jQuery ajax call is made like that:
$('#export_selected').click(function(){
var checked = $('.select_rows:checked');
var ids = [];
$.each(checked, function(index, value){
ids.push(value.id);
})
$.ajax({
method : "POST",
url : "{{URL::to('/spot/exportTable')}}",
data : {ids:ids}
});
});
And then the php method is defined that way:
public function exportTable(Request $req) {
$spots = array_flatten($req->all());
$res = Spot::whereIn('id', $spots)->get();
Excel::create('Spots', function($excel) use($res) {
$excel->setTitle('Title goes here');
$excel->setCreator('Creator Goes Here')->setCompany('Company Goes Here');
$excel->sheet('Excel sheet', function($sheet) use($res) {
$sheet->setOrientation('landscape');
$sheet->fromArray($res);
});
})->store('csv', storage_path('/exports', true));
$file = base_path() . '/storage/exports/Spots.csv';
$headers = ['Content-Type: application/csv', 'Content Description: File Transfer', 'Cache-Control: must-revalidate, post-check=0, pre-check=0'];
return response()->download($file, 'Spots.csv' , $headers);
}
Chrome developer console prints the results as raw lines.
The file is successfully exported and created in the disk.
The path to file is correct.
But the download is never started.
Echoing the response gives:
HTTP/1.0 200 OK
0: Content-Type: application/csv
Cache-Control: public
Content-Disposition: attachment; filename="Spots.csv"
Date: Mon, 26 Oct 2015 16:08:26 GMT
Last-Modified: Mon, 26 Oct 2015 16:08:26 GMT
1: Content-Description: File Transfer
2: Cache-Control: must-revalidate, post-check=0, pre-check=0
I put the answer here for everybody having the same issue.
#manix figured it out: I'm trying to download via Ajax, which needs to be done in another way, not the way I wrote my code

NSHTTPCookie cookiesWithResponseHeaderFields

When making a call to an API, I receive this as response:
<NSHTTPURLResponse: 0x7f96f0510f80> { URL: https://insula.magister.net/api/sessie } { status code: 201, headers {
"Cache-Control" = "max-age=120, private";
"Content-Length" = 0;
Date = "Thu, 30 Jul 2015 17:27:11 GMT";
"Set-Cookie" = "SESSION_ID=c8714acb-22f8-4295-90ee-82e9469890e1; domain=insula.magister.net; path=/api; secure; httponly";
"Strict-Transport-Security" = "max-age=31536000";
Vary = "Accept-Encoding,Cookie";
"X-Frame-Options" = DENY;
} }
print(HTTPResponse.allHeaderFiles) prints the following output:
[Set-Cookie: SESSION_ID=65a59001-de75-41ff-ad22-70549baa96f5; domain=insula.magister.net; path=/api; secure; httponly, Strict-Transport-Security: max-age=31536000, Date: Thu, 30 Jul 2015 17:33:13 GMT, X-Frame-Options: DENY, Content-Length: 0, Cache-Control: max-age=120, private, Vary: Accept-Encoding,Cookie]
But I can't get cookiesWithResponseHeaderFields to work, I should pass a [String:String] array as first parameter, but the response doesn't seem to meet.
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(HTTPResponse.allHeaderFields, forURL: url)
But as HTTPResponse.allHeaderFiles is an array of type [NSObject:AnyObject] it can't meet the [String:String] parameter type.
Who knows what to do?
There's a similar question with a great answer.
You should cast the allHeaderFields property to the type you need, that is [String:String], like this:
let foundCookies: [NSHTTPCookie]?
if let responseHeaders = HTTPResponse.allHeaderFields as? [String:String] {
foundCookies = NSHTTPCookie.cookiesWithResponseHeaderFields(responseHeaders, forURL:url)
}

How to fix System.ArgumentException in HttpWebResponse?

I am facing this exception when receiving HttpWebResponse for my WindowsPhone app. How am I supposed to fix this. It happens very often but I need to make sure my app doesn't crash if it happens. Please have a look at the screenshot.
My expected response is
Headers:-
HTTP/1.1 500 Internal Server Error
Date: Wed, 28 Nov 2012 06:41:24 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Keep-Alive: timeout=30
Set-Cookie: ...........; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Internal Server Error:
Json:-
{"status":0,"error_code":1001,"data":{"msg":"Something went wrong. Please try again later. [error code 1001]"}}
It also shows in the InnerException the message as Specified value has invalid HTTP Header characters.
Parameter name: name
Please help. I don't know why webRequest.EndGetResponse(asynchronousResult) is not able to read the response. Is there an alternative?
UPDATE
to start the request:
_webRequest.BeginGetRequestStream(new AsyncCallback(GetReqeustStreamCallback), _webRequest);
private void GetReqeustStreamCallback(IAsyncResult asynchronousResult)
{
if ((!ReqIdEnabled || Network.RequestUniqueId == this.RequestUniqueId))
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
// End the stream request operation
using (Stream postStream = webRequest.EndGetRequestStream(asynchronousResult))
{
// Add the post data to the web request
postStream.Write(_postDataInBytes, 0, _postDataInBytes.Length);
//postStream.Dispose();
}
// Start the web request
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
try
{
//**throws Exception here when my server returns 503/500 and is not caught by the catch block below**
using (HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult))
{
ReadResponse(response);
}
}
catch (WebException ee)
{
}
}
Put a breakpoint in your catch block, and look at the lower level stacks, and look for System.Net.ni.dll!System.Net.WebHeaderCollection.this[string].set(string name, string value).
In the local variables, you can see for which particular value, the parse is failing.
For me, It was Google App Engine's custom User-Agent header which was creating the problem.

CouchDB: Get server-time with an http request in CouchApp

I need the server-time for "user-is-online" stats in my CouchApp. I work with jquery.couch.js and would prefer to have a url, e.g. /db/_design/app/time - which gets me a timestamp.
How do I realize this?
A show function could do that:
function(doc, req) {
// _design/myapp/_show/now
// First version possibly incompatible with some spidermonkey versions.
//var now = new Date();
var now = new Date().getTime();
var output = JSON.parse(JSON.stringify(now)) + "\n";
return { code: 200
, headers: { "Content-Type": "text/plain"
}
, body:output
};
}
The server also includes a Date header that you might want to use.
$ curl -D- http://localhost:5984
HTTP/1.1 200 OK
Server: CouchDB/1.1.0 (Erlang OTP/R14B)
Date: Fri, 27 May 2011 00:28:31 GMT
Content-Type: text/plain;charset=utf-8
Content-Length: 40
Cache-Control: must-revalidate
{"couchdb":"Welcome","version":"1.1.0"}

Resources