can't get a response out of eBay's Merchandising API - webservice-client

This is my first question.. ever... for this illustrious and reverential forum, so if I am rebuked for the content of this question I won't take it personally...
I am attempting to call ebay's merchandising service via the code below, and keep getting a "The request failed with an empty response." err Response
static void Main(string[] args)
{
//Use the custom class
customMerchandisingService svc = new customMerchandisingService();
//Set the production URL
svc.Url = "http://svcs.ebay.com/MerchandisingService?";
GetMostWatchedItemsRequest request = new GetMostWatchedItemsRequest();
request.categoryId = "617";
MerchandisingServiceItemResponse response = svc.getMostWatchedItems(request);
foreach (Item item in response.itemRecommendations)
{
//process results
string title = item.title;
string itemID = item.itemId;
}
}
class customMerchandisingService : MerchandisingAPI.MerchandisingService
{
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest req = (HttpWebRequest)base.GetWebRequest(uri);
//Set the AppID, Operation, Service, Protocol and Version as HTTP Headers
req.Headers.Add("EBAY-SOA-CONSUMER-ID", "Your AppID");
req.Headers.Add("X-EBAY-SOA-OPERATION-NAME", "getMostWatchedItems");
req.Headers.Add("X-EBAY-SOA-SERVICE-NAME", "MerchandisingService");
req.Headers.Add("X-EBAY-SOA-MESSAGE-PROTOCOL", "SOAP11");
req.Headers.Add("X-EBAY-SOA-SERVICE-VERSION", "1.1.0");
return req;
}
}
I googled a bit, and read posts such as the following:
"The request failed with an empty response" when calling a web service
I tried playing with my httpeepee's, and keep coming up short. Basically I was hoping that it wasn't me, that some web developer at eBay (bless his heart) was to blame, today at least.
I guess I was hoping someone on this forum that also develops against eBay's API's could confirm that the merchandising service is working fine for them today, in which case I guess I'll need to keep banging my head against a wall.
Thanks in advance.

Related

Unable to insert data using POST request - Spring REST

I am making a simple project that uses a Spring RESTApi. I tried to insert data into database using POST request but unfortunately got error there.
I am using Postman for API request.
All other request get, delete and put works fine but post doesn't work.
i have tried inserting data manually without using api but that works fine for me.
The error is;
#RequestMapping(value = "/create", method = RequestMethod.POST)
public ResponseEntity<Void> createUser(#RequestBody User user, UriComponentsBuilder ucBuilder) {
try {
userService.insert(user);
} catch (HibernateException e) {
System.out.println(e);
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getUserId()).toUri());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
POSTMAN
Thanks!!!!!!!!!!!!!!

Apache Camel - from jms to http

I have a spring-boot project using Apache Camel.
I want to read a message from an activemq queue containing a file and send it to a web server.
I am trying to find the proper way to do this.
I believe I can make something like:
from("activemq:queue").bean(MyBean.class, "process")
And manually build a http request but I can't help thinking there is probably a better way to do it. Like:
from("activemq:queue").bean(MyBean.class, "process")
.setHeader(Exchange.HTTP_METHOD,constant("POST"))
.to("http://localhost:8080/test");
But I don't know how to manipulate the "exchange" to have a valid http Message.
MyBean receives an Exchange object containing a JmsMessage. I see that there is also a HTTPMessage but I don't think I should build that manually. (It requires HTTPRequest and Response objects I am not sure how to get.)
Can someone shed some light on this problem?
Update
I am going for the bean solution.
from("activemq:queue").bean(MyBean.class, "sendMultipart");
public void sendMultipart(Exchange exchange) {
ByteArrayInputStream in = new ByteArrayInputStream((byte[]) exchange.getIn().getBody());
InputStreamBody contentBody = new InputStreamBody(in, ContentType.create("application/octet-stream"), "filename");
HttpEntity entity = MultipartEntityBuilder
.create()
.addPart("file", contentBody)
.build();
HttpPost httpPost = new HttpPost("http://localhost:8080/upload/");
httpPost.setEntity(entity);
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse);
} catch (IOException e) {
e.printStackTrace();
}
}
Updated post
I found this http://hilton.org.uk/blog/camel-multipart-form-data. It allows you to leverage the camel http component.
"jms:queue/SomeQ" ==> {
process(toMultipart)
setHeader(Exchange.CONTENT_TYPE, "multipart/form-data")
process((e: Exchange) => e.getIn.setHeader(Exchange.HTTP_URI,"http://localhost:8111/foo"))
to ("http:DUMMY")
}
def toMultipart(exchange: Exchange): Unit = {
val data = exchange.in[java.io.File]
val entity = MultipartEntityBuilder.create()
entity.addBinaryBody("file", data)
entity.addTextBody("name", "sample-data")
// Set multipart entity as the outgoing message’s body…
exchange.in = entity.build
}
Side note: this would really be a nice use-case to try-out reactive streams.
Original post
I am still having some problems understanding your actual problem. Perhaps some code might help:
I am now assuming you are receiving bytes in some character encoding and want to sent it onward to a dynamically established http-endpoint.
Is the following something you are looking for (code is in camel's scala-dsl)
"jms:queue/SomeQ" ==> {
convertBodyTo(classOf[String],"UTF-32" )
process((e: Exchange) => e.in = e.in[String].toUpperCase + "!")
process((e: Exchange) => e.getIn.setHeader(Exchange.HTTP_URI,"http://localhost:8111/foo"))
to ("http:DUMMY")
}
It will be send as an HTTP POST as the body is not null.
I receive it all well on another endpoint i created to ensure the code above is correct:
"jetty:http://localhost:8111/foo" ==> {
log("received on http 8111 endpoint ${body}")
}

GWT dealing with request error

I have a GWT module and in it I navigate to a different URL via:
Window.Location.assign(url);
The navigated url is then handled by a servlet, up until this point if there was an error it was handle by the resp.sendError methode
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed.");
Which would then navigate to the browsers error page. However I wanted to know is there away I can not navigate to an error page? i.e. I would be able to check in my GWT code if there was an error and then do something? Like resend the request ect.
Thanks!
When you navigate away from your webapplication that's that. Instead of using Window.Location.assign you should make an HTTP request still from your webapplication, for example using RequestBuilder.
Example from the docs mentioned earlier:
import com.google.gwt.http.client.*;
...
String url = "http://www.myserver.com/getData?type=3";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP violation, etc.)
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// Process the response in response.getText()
} else {
// Handle the error. Can get the status text from response.getStatusText()
}
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
Note that this will work only if your servlet and webapplication are on the same address (domain, port, protocol), because of Same Origin Policy. If that's not the case, there are still some options, like JSON with padding (which GWT supports via JsonpRequestBuilder).

Web API Async Upload with XmlHttpRequest to get progress

I'm trying to drag and drop file upload with a progress bar.
I have a div which is listening to files being dropped on which is working perfectly.
I'm then..
//Setting up a XmlHttpRequest
xhr = new XMLHttpRequest();
//Open connection
xhr.open("post", "api/ImageUpload", true);
// Set appropriate headers
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Type", uf.type);
xhr.setRequestHeader("X-File-Name", uf.name);
xhr.setRequestHeader("X-File-Size", uf.size);
This sends fine, with the stream as the body of the request to the Web API (not async).
[System.Web.Mvc.HttpPost]
public string Post()
{
Stream stream = HttpContext.Current.Request.InputStream;
String filename = HttpContext.Current.Request.Headers["X-File-Name"];
FileModel file = uploadService.UploadFile(stream, filename);
return file.Id.ToString();
}
I'm trying to chance the request to "public async Task< string> Post(){ }
If the method was using a multipart form on the page instead of XmlHttpRequest I would have used "await Request.Content.ReadAsMultipartAsync(provider)" but this doesn't seem to be populated at the time I need it.
So what is the correct was to handle and an Async call from XmlHttpRequest on a Web API in order to record progress during the request with XHR's progress event?
I have looked at a great deal of pages so far to find a solution but this is the page I have used primarily.
http://robertnyman.com/html5/fileapi-upload/fileapi-upload.html
Thanks for any help
Oliver
It looks like someone else had the same question with you and got an answer yet. please have a look at ASP.NET MVC 4 Web Api ajax file upload.
And here is an example from microsoft http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2.
I combined the two above solution together and worked for me (just adjust a little bit)
one line change in Javascritp
xhr.open("post", "api/upload", true);
Save the file using stream
public class UploadController : ApiController
{
public async Task<HttpResponseMessage> PostFormData()
{
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var fileName = Path.Combine(root, Request.Headers.GetValues("X-File-Name").First());
try
{
var writer = new StreamWriter(fileName);
await Request.Content.CopyToAsync(writer.BaseStream);
writer.Close();
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}

HttpGet not returning anything - android

I'm trying to setup an HTTP connection using the HttpGet but i'm not getting anything back from the website. The only text on the website is a string reading: "Error: Username not passed". I have looked at other questions/answers regarding this issue, but they go into parsing the JSON format. However, I'm just interested in viewing what i'm getting back in the response. Is this possible? Does the android code only accept a response in the JSON format? If so, doesn't this include a string similar to the one I should be getting back from the website? What am I missing? Here's the code I have:
public void onClick(View v) {
//Create a default HTTPClient to setup retrieve data functionality
httpclient = new DefaultHttpClient();
//Create new HTTP GET with URL to php file
httpget = new HttpGet("http://satpreet.com/mobile/auth.php");
try {
response = httpclient.execute(httpget);
entity = response.getEntity();
InputStream instream = entity.getContent();
resultdata = convertStreamToString(instream);
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Hit Exception", Toast.LENGTH_LONG).show();
}
//For viewing the result
LinearLayout lView = new LinearLayout(this);
TextView myText = new TextView(this);
myText.setText(resultdata);
lView.addView(myText);
setContentView(lView);
The last part is probably not the best way to debug my code. Can you suggest a better way? I tried using the log.i however when I set up a filter to by Log Tag, nothing is caught.
Thank you.
Did you add the required permission
<uses-permission android:name="android.permission.INTERNET"/>
to the AndoridManifest?
Maybe also change this:
httpclient.execute(httpget);
to:
httpclient.execute(httpget, new BasicHttpContext());
Also notice that you have to use this code asynchronously. Otherwise you'll get some exceptions while running on a real device.

Resources