Unable to send post request via cpp-netlib - c++

I am using cpp-netlib-0.9.4 with Visual Studio 2010. I have a function make_header which is like this:
http::client::request* Interface::make_request_header(const string& uri) {
string url = host_ + uri;
string json_type = "application/json";
http::client::request* req = new http::client::request(url);
req->add_header(make_pair("X-AUTH-TOKEN", token_));
req->add_header(make_pair("Content-Type", json_type));
req->add_header(make_pair("Accepts", json_type));
return req;
}
A get request works perfectly fine, which is something like:
http::client client;
http::client::request* req = make_request_header(my_uri);
http::client::response res = client.get(*req);
But a POST request throws an exception/core-dump. I have checked it multiple times otherwise and it seems to work every time on chrome dev http client extension. The URL I use for post request is:
http://myhost.com/commands?query=my query
In the above example, I try
http::client client;
http::client::request* req = make_request_header("http://myhost.com/commands?query=my query");
http::client::response res = client.post(*req); // FAILS AT THIS STEP.
Any ideas why?

A query parameter can not contain spaces, you have to URL-encode it.
Space is %20 to your query should look like
http://myhost.com/commands?query=my%20query

Related

Grapevine RestClient Json Body

I'm having difficulty putting together a request by sending a json content, can not find anything in the 4.x documentation it's completely different from version 3.x
RestClient client = new RestClient();
client.Host = "localhost";
client.Port = 8080;
RestRequest request = new Grapevine.Client.RestRequest("/route1");
request.HttpMethod = HttpMethod.POST;
RestResponse response = client.Execute(request) as RestResponse;
Somewhere in your code - prior to sending your request - you need to set the body (or payload) of your request.
request.Payload = "send this data";
The payload is just a string, so it's up to you to serialize your objects to a JSON string before making the assignment (and set the ContentType property appropriately). The Json.NET library is widely used to accomplish this. You can also do this by hand:
request.ContentType = ContentType.JSON;
request.Payload = "{\"key\":\"value\"}";

Why am I not recieving facebook graph entity_id value from http get request?

if I do a simple HTTP GET request with e.g. POSTMAN then in the response there's an element called 'entity_id'.
e.g. https://www.facebook.com/yourFacebookName
If however, I do the request from a simple C# app then the following code doesnt return the 'entity_id' element in the response and I cant figure out why?
Code from app:
string html = string.Empty;
string url = string.Format("https://www.facebook.com/{0}", "yourFBName");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
if (html.Contains("entity_id"))
{
//do some stuff
}
Anyone know why its dropping the 'entity_id' element, but returning it when hitting that url from POSTMAN etc?

connection.getConnetion() returns 404 code on WebSphere7

I have implemented a REST service using Spring Integration.
When I try to access the service manually using main function, It is working fine.
I also tested the service using REST Client in Google Chrome and that worked. But the service is coming back with responseCode 404 on WebSphere server. So I am facing the issue when I deploy the code on higher environment.
URL u = new URL("http://localhost:8080/MyApplication/testRestService");
URLConnection uc = u.openConnection();
HttpURLConnection connection = (HttpURLConnection) uc;
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept","*/*");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);
//helper function that gets a string from a dom Document
String input = jsonInput;
wout.write(input.getBytes());
wout.flush();
wout.close();
// Response
int responseCode = connection.getResponseCode();
Is is dependent on server, so its coming back with response code 404 ? Do we need any server side configuration ?
Any suggestion will be appreciated.
Why do you use different ContentType for URLConnection and for httpClient?
Show, please, your REST service config: 404 means Not found. Therefore you use (or don't) some options in request which makes it non-matching for the server's RequestMapping.
I tried with Apache HTTP Client and the code is working on WebSphere now. Still I am not able to find the reason why java.net.HttpURLConnection was not working on WebSphere.
Please find my updated code below :
DefaultHttpClient httpClient = null;
HttpPost postRequest = null;
StringEntity inputEntity = null;
HttpResponse response = null;
try{
//RETREIVE WEB SERVICE URL FROM DB
String callbackURL = "http://localhost:8080/MyApplication/testRestService";
httpClient = new DefaultHttpClient();
postRequest = new HttpPost(callbackURL);
String inputData = request.toString();
inputEntity = new StringEntity(inputData);
inputEntity.setContentType("application/x-www-form-urlencoded");
postRequest.setEntity(inputEntity);
response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201 && response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "+ response.getStatusLine().getStatusCode());
}
//System.out.println("HTTP Response Code :"+response.getStatusLine().getStatusCode());
LOGGER.debug("HTTP Response Code :"+response.getStatusLine().getStatusCode());
httpClient.getConnectionManager().shutdown();
}catch(IOException ex){
ex.printStackTrace();
throw ex;
}finally{
httpClient.getConnectionManager().shutdown();
httpClient = null;
postRequest = null;
inputEntity = null;
response = null;
}

How to send http get request to servlet from restful webservice?

I am beginner in that, but
I have a restful web service and i want to send a http get request from it and handle the response in it. if any one knows how can i do this ?
i tried this :
#Context private HttpServletRequest servletRequest;
#Context private HttpServletContext servletContext;
but i want to know what's this injection will return to me? i don't understand how will get it and it's scope, and how to get the response?!
and how i will send the request?
i found this http client apache
and here is an example for sending an Get request and getting the response
http://www.mkyong.com/java/apache-httpclient-examples/
String url = "http://www.google.com/search?q=httpClient";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
i'll try and post any helpful edits i reach, anyone have another helpfull comments or edits please do.

Displaying file: MessageBodyReader not found for media type=application/octet-stream

My requirement is that I should display a file using RESTFul services. Here how I proceeded:
Server:
#GET
#Path("/{name}")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile {
...
return Response.ok(inputStream).header("Content-Disposition", "attachment; filename=" + fileName).build();
Client:
final WebTarget target = createRestClient("path/" + fileName, new HashMap<String, Object>());
return target.request(MediaType.APPLICATION_OCTET_STREAM).get().readEntity(Part.class);
When I run it, I've got this error:
MessageBodyReader not found for media type=application/octet-stream, type=interface javax.servlet.http.Part, genericType=interface javax.servlet.http.Part.
Do you have any idea where did this come from?
Thanks.
javax.servlet.http.Part should be used to obtain upload multipart data, and is created by the servlet container, which you obtain from a HttpServletRequest. It should not be used in this way. Beside the data is not even multipart.
Instead, you can simply get the InputStream from the from the Response and the Content-Dispostion get explicitly from the header. Something like
Response response = target.request()
.accept(MediaType.APPLICATION_OCTET_STREAM)
.get();
// get InputStream
InputStream is = response.readEntity(InputStream.class);
// get Content-Disposition header
String contentDisposition = (String)response
.getHeaderString(HttpHeaders.CONTENT_DISPOSITION);
// get filename
contentDisposition = contentDisposition
.substring(contentDisposition.indexOf("filename=") + "filename".length() + 1);
System.out.println(contentDisposition);