how to insert cypher statement in http post request - java

I have just started with neo4J and wanted to try the transactional cypher endpoint. I have my neo4J server running on localhost:7474/ and have inserted the movie data.
As stated in the documentation, I have to do a post request and include some parameters. Unfortunately I don't know how I have to include my query in the POST request. As far as I have understood it, I have to pass a JSON String.
private static String sendPost() throws Exception {
String url = "http://localhost:7474/db/data/transaction";
String statement ="[ { \"statement\" : \"MATCH (n:Person) RETURN n.name, n.born\"} ]";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("Accept", "application/json; charset=UTF-8"));
urlParameters.add(new BasicNameValuePair("Content-Type", "application/json"));
urlParameters.add(new BasicNameValuePair("statements", statement));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
StringBuilder builder = new StringBuilder();
builder.append("\nSending 'POST' request to URL : " + url+"<br>");
builder.append("Post parameters : " + post.getEntity()+"<br>");
builder.append("Response Code : " + response.getStatusLine().getStatusCode()+"<br>");
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
result.append("<p>");
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line+"\n");
}
result.append("</p>");
return builder.toString();
}
When I execute the code, I get the following output:
Sending 'POST' request to URL : http://localhost:7474/db/data/transaction
Post parameters : org.apache.http.client.entity.UrlEncodedFormEntity#76adb5f6
Response Code : 415
Can anyone help me on how I have to include my query in the POST request?

http://docs.neo4j.org/chunked/stable/rest-api-transactional.html
Looking at that, you can see the body of your POST request isn't what the server is expecting, i.e. you should be sending an entire JSON document, and not a k/v pair w/ "statements" as a key and your JSON Cypher query as the value. Remember you're sending JSON here, and not a URLEncoded body.
Also, it looks like you're setting the "Accept" and "Content-Type" k/v pairs as part of the POST body when they should, in fact, be part of the headers.
Also also, consider using the Cypher endpoint: http://docs.neo4j.org/chunked/stable/rest-api-cypher.html
HTH

Related

How to write / convert CURL for Android java

I am trying to implement the MOT history API https://dvsa.github.io/mot-history-api-documentation/ and they give an example using CURL which works with the supplied api key successfully when using an online CURL tool.
I am trying to implement this in Android and realise I have to use something like HttpPost rather than CURL, this is my code:
//Tried with full URL and by adding the registration as a header.
//HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests?registration=" + reg_selected);
HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json+v6");
httpPost.addHeader("x-api-key", "abcdefgh123456");
httpPost.addHeader("registration", reg_selected);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
InputStream inputStream = response.getEntity().getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = bufferedReader.readLine();
String jsonStr = readLine;
JSONObject myJsonObj = new JSONObject(jsonStr);
}else if (response.getStatusLine().getStatusCode() == 400){
//Bad Request Invalid data in the request. Check your URL and parameters
error_text = "Bad Request";
}else if (response.getStatusLine().getStatusCode() == 403){
//Unauthorised – The x-api-key is missing or invalid in the header
error_text = "Authentication error"; //<<<< FAILS HERE 403
}
response.getStatusLine().getStatusCode() returns • "403 – Unauthorised – The x-api-key is missing or invalid in the header".
However the x-api-key that I use works correctly with the online CURL test so the actual key is correct but how I am adding it to my android code request must be invalid or similar.
Can anyone throw any light as to the correct way to convert the CURL into Android java so that the server does not return 403?
Thanks
It's easy to do with Jsoup:
// CREATE CONNECTION
Connection conn=Jsoup.connect("URL_GOES_HERE");
// ADD POST/FORM DATA
conn.data("KEY", "VALUE");
// ADD HEADERS HERE
conn.header("KEY", "VALUE");
// SET METHOD AS POST
conn.method(Connection.Method.POST);
// ACCEPT RESPONDING CONTENT TYPE
conn.ignoreContentType(true);
try
{
// GET RESPONSE
String response = conn.execute().body();
// USE RESPONSE HERE
// CREATE JSON OBJECT OR ANYTHING...
} catch(HttpStatusException e)
{
int status = e.getStatusCode();
// HANDLE HTTP ERROR HERE
} catch (IOException e)
{
// HANDLE IO ERRORS HERE
}
Ps: I guess you are confused with Header and Post Data. The key etc (Credentials) must be used as Post Data and Content Type etc as Header.

HttpResponse with special characters

I have written a REST client for this endpoint:
textmap.com/ethnicity_api/api
However, while passing it a name string like jennífer garcía in the POST params, and setting encoding to UTF-8, the response that I get is not the same string. How to get the same name in the response object?
Below is how I set the request and the response thatI get:
httpClient = HttpClients.createDefault();
httpPost = new HttpPost(baseurl);
StringEntity input = new StringEntity(inputJSON, StandardCharsets.UTF_8);
input.setContentType("application/json");
//input.setContentType("application/json; charset=UTF-8");
httpPost.setEntity(input);
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
output = org.apache.commons.io.IOUtils.toString(br);
System.out.println(output);
Value of the name in output is : jenn�fer garc�a
This is a completely different charset from what I had sent in the request. How can I get the same charset as I had sent in request?
Secondly, I want the same code to work in both Java-6 and Java-7. The above code is using Java-7 only. How can I make the code work for both these versions?
I think the BufferedReader is breaking the UTF8 encoding, so this is actually pretty unrelated to HTTP. On a side note, the br may not be needed at all.

HTML client for cxf rest service with #HeaderParam & List<Attachment>

I have cxf rest service with #HeaderParam and List Attachment as parameters. I have to create html client to invoke the service. Could anyone help me in how to set the headerparams because when I hit the service I get the following exception
java.lang.RuntimeException: org.apache.cxf.interceptor.Fault: value can't be null for parameter param1
as this parameter is set #NotNull&NotBlank and is not able to find in the header.
This exception because required header is not available as a part of HttpRequest header.
you have to cook-up your code to set the custom header. Something like below code, So that your REST resource will consume the parameter from incoming request header
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("Your URL");
//Adding custom headers
request.addHeader("HEADER_NAME", "VALUE");
HttpResponse response = client.execute(request);
System.out.println("Http Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
result.append(line);
}

HTTP/1.1 400 Bad Request in java HTTP post

I am trying to post xml data to API using HTTP post method with credentials but a getting HTTP/1.1 400 Bad Request error .. Can anyone pl help me out ....
Here is my sample code:
BufferedReader br = new BufferedReader(new FileReader(new File("Data.xml")));
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!= null){
sb.append(line.trim());
}
System.out.println("xml: "+sb);
params=sb.toString();
HttpPost request = new HttpPost("*****************url***************");
String urlaparam=URLEncoder.encode("importFormatCode:1&data:"+params,"UTF-8");
String userCredentials = "****:******";
byte[] auth = Base64.encodeBase64(userCredentials.getBytes());
StringEntity entity=new StringEntity(urlaparam);
request.addHeader("Content-type","application/x-www-form-urlencoded");
request.addHeader("Accept", "application/xml");
request.addHeader("Accept-Language", "en-US,en;q=0.5");
request.addHeader("Authorization", "Basic " + new String(auth));
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine());
System.out.println(request);
}
catch(Exception e)
{
}
First of all, your form parameters are not encoded correctly. You are using colon (:) to separate keys from their values, but instead, the equal sign (=) must be used:
Wrong: "importFormatCode:1&data:" + params
Correct: "importFormatCode=1&data=" + params
(See also W3C.org - Forms in HTML Documents - application/x-www-form-urlencoded)
Apart from that, you must not URL-encode the entire string but only the keys and the values. Otherwise you'll also encode the separator characters = and &!
The easiest way is to use the existing utility class org.apache.http.client.utils.URLEncodedUtils (assuming that you're using Apache HTTP Components):
String xmlData = // your xml data from somewhere
List<NameValuePair> params = Arrays.asList(
new BasicNameValuePair("importFormatCode", "1"),
new BasicNameValuePair("data", xmlData)
);
String body = URLEncodedUtils.format(params, encoding); // use encoding of request
StringEntity entity = new StringEntity(body);
// rest of your code

HTTP post JSON java

I'm trying to post some json data using a http post method within my android application however i cannot seem to get it to work, the string is building fine and it works if i test using google chrome addon advanced rest client. I'm not the strongest with JSON hence why it is a string and not a JSON object. The Post request does not execute. Thanks in advance
String json = "{\"data\": [";
for (String tweet : tweetContent)
{
json = json + "{\"text\": \"" + tweet + "\", \"query\": \"" + SearchTerm + "\", \"topic\": \"movies\"},";
}
json = json.substring(0, json.length() - 1);
json = json + "]}";
Log.i("matt", json);
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.sentiment140.com/api/bulkClassifyJson?appid=matt-43#hotmail.com");
StringEntity entity = new StringEntity(json, HTTP.UTF_8);
httppost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.i(LOG_TAG, responseBody);
sentiments.add(responseBody.toString());
what is the response code that you are getting back after posting from the Http client.
It should be 200 for a successful Http post. Other wise there is some issue.
You are posting the JSON data to the URL. which application is reading this data from the URL. Is there some servlet on the other application that is reading JSON data fromrequest. check that and see.
Also check the request headers for the Http Post request. if you are setting all the request headers properly.

Categories

Resources