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.
Related
I want to consume rest api from url with http basic authentication that returns a big json & then i want to parse that json without POJO to get some values out of it. How can i achieve that in java spring?
I know this is common question but i could not get proper solution that worked for me.
Please help me someone.
Using the Apache HttpClient, the following Client Code snipped has been copied from the following URL. The comments have been added by myself.
https://www.baeldung.com/httpclient-4-basic-authentication
HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
// Combine the user and password pair into the right format
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
// Encode the user-password pair string in Base64
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.ISO_8859_1));
// Build the header String "Basic [Base64 encoded String]"
String authHeader = "Basic " + new String(encodedAuth);
// Set the created header string as actual header in your request
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
I am trying to send SMS messages when a button is clicked in an Android app. I have the SMS sending code in Python using a REST API. The template looks like so:
import requests
url = "https://api.apidaze.io/{{api_key}}/sms/send"
querystring = {"api_secret":"{{api_secret}}"}
payload = "from=15558675309&to=15551234567&body=Have%20a%20great%20day."
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.request("POST", url, data=payload, headers=headers,
params=querystring)
print(response.text)
Because I am making an Android app, I need this to be in Java, but I am having trouble making the same POST request with the same parameters, headers, and body in JAVA.
Does anyone know how to make convert this template into something I can use for an Android app in Java?
There is a port of Apache Http Client for Android:
http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html
Check the documentation, a simple POST request is very easy using this library:
HttpPost httpPost = new HttpPost("https://api.apidaze.io/" + api_key + "/sms/send");
String json = "{"api_secret":" + api_secret + "}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
CloseableHttpResponse response = client.execute(httpPost);
I am trying to create a playlist using the Spotify API, and I am writing the POST request to the Spotify API endpoint in Java. I have also included every available scope from Spotify when I retrieve my access token. This is returning a response with an error message of:
{"error":{"message":"Error parsing JSON.","status":400}}
Here is what I have:
String http = "https://api.spotify.com/v1/users/" + userId + "/playlists";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(http);
JsonObject entityObj = new JsonObject();
JsonObject dataObj = new JsonObject();
dataObj.addProperty("name", "title");
dataObj.addProperty("public", "false");
entityObj.add("data", dataObj);
String dataStringify = GSON.toJson(entityObj);
StringEntity entity = new StringEntity(dataStringify);
post.setEntity(entity);
post.setHeader("Authorization", "Bearer " + accessToken);
post.setHeader("Content-Type", "application/json");
CloseableHttpResponse response = client.execute(post);
System.out
.println("Response Code : " + response.getStatusLine().getStatusCode());
String resp = EntityUtils.toString(response.getEntity());
JSONObject responseObj = new JSONObject(resp);
System.out.println(responseObj);
client.close();
Please let me know if you have any insights into what is wrong.
I am assuming you are using the org.json library as well as Google's Gson library. Using both doesn't make sense in this context. You won't need
String dataStringify = GSON.toJson(entityObj);
as entity Object already is a JSON Object. entityObj.toString() should be enough.
The current JSON Data you are sending looks like this:
{
"data":
{
"name":"title",
"public":"false"
}
}
Spotify ask for an JSON Object like this:
{
"name": "New Playlist",
"public": false
}
You only have to send the Data Object dataObj.
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
I have to pass xml in a request, but I cannot figure out how can I perform it :/. Can you please help me?
I've already stored and prepared the xml.
The request sample:
POST http://..... HTTP/1.0
Content-type: text/xml
and xml
Thanks in advance
What is the source and destination of your xml?
If your source is say a file, and your destination is say a servlet, you can use curl http://en.wikipedia.org/wiki/CURL to send the xml and a servlet to receive it.
The servlet 3.0 spec has new features for this kind of stuff so that should make it easy.
OR
Are you trying to send a post from your java application?
John : )
Use HttpClient
Following is the code I use to post xml to a server.
String payload = <XML String>
HttpPost post = new HttpPost("http://" + ip + ":" + port);
LOGGER.info("WebService Call for " + ip + ":" + port);
try {
StringEntity entity = new StringEntity(payload);
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
HttpEntity resEntity = response.getEntity();
EntityUtils.consume(resEntity);
} finally {
post.releaseConnection();
}