Posting JSON object to HTTP server - java

So I'm developing an Android app (Java) that posts a JSON object to a web server. I've achieved this, but I'm battling to get the string value to display properly.
Instead of the server receiving "6666666666666", it receives "Ljava.lang.String;#41108be0]". How on earth do I go about fixing this? Here's my code:
protected Boolean doInBackground(String... ID) {
HttpClient httpClient = new DefaultHttpClient();
Date dateTime = new Date();
string deviceID=null;
try {
HttpPost request = new HttpPost("http://192.168.1.89:80/");
JSONObject json = new JSONObject();
json.put("IDNo", ID.toString());
json.put("DTSent", dateTime);
json.put("DeviceID", deviceID);
StringEntity se = new StringEntity(json.toString(), "UTF-8");
se.setContentType("application/json; charset=UTF-8");
request.setEntity(se);
request.setHeader( "Content-Type", "application/json");
}
Please help.

ID is a String-Array not just a string. the ... makes it an array. so either use ID[0] or remove the ... from the function declaration

You are passing in an array of strings (see the three dots?). Try using ID[0] instead.
Here is a useful post:

Related

use docusign api creates envelopes, error: Object moved

I consulted the API documentation and sent it successfully in api explorer-> Envelopes: create. I also got json & request path & token. I used httpclient post in java and received Object moved Object moved to here . Does anyone know what I missed?
`
DocsignDocument docsignDocument = new DocsignDocument();
docsignDocument.setDocumentBase64
docsignDocument.setDocumentId("1");
docsignDocument.setFileExtension("pdf");
docsignDocument.setName("Test.pdf");
list.add(docsignDocument);
Recipients recipients = new Recipients();
Signers signers = new Signers();
signers.setEmail("xxxx");
signers.setName("Qin");
signers.setRecipientId("1");
Signers signers1 = new Signers();
signers1.setEmail("xxx#qq.com");
signers1.setName("OYX");
signers1.setRecipientId("2");
List<Signers> signersList = new ArrayList<>();
signersList.add(signers);
signersList.add(signers1);
recipients.setSigners(signersList);
dataJson.put("documents",list);
dataJson.put("emailSubject","TEST");
dataJson.put("recipients",recipients);
dataJson.put("status","sent");
String data = dataJson.toJSONString();
String results2 = HttpDocusignUtils.httpPostJson("https://account-d.docusign.com/restapi/v2.1/accounts/xxx/envelopes",access_token,data)`
post request:
public static String httpPostJson(String uri, String token, String obj) {
String result = "";
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", "application/json"); // 添加请求头
httpPost.addHeader("Authorization","Bearer "+token);
httpPost.addHeader("Accept-Encoding","gzip,deflate,sdch");
httpPost.setEntity(new StringEntity(obj));
System.out.println(httpPost);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
result = convertStreamToString(instreams);
System.out.println(result);
}
} catch (Exception e) {
e.getMessage();
}
return result;
}
https://account-d.docusign.com/restapi/v2.1/accounts/xxx/envelopes is not a valid DocuSign endpoint.
The Account Server (account-d.docusign.com) is used to get a token and make a UserInfo call to determine the correct base URL for a particular account.
Because you're in the Demo environment, your base url will begin with https://demo.docusign.net
Well, one issue is that the the Document model in Java is Document from
import com.docusign.esign.model.Document;
To debug, I suggest using the DocuSign API logging feature. Then update (edit) your question to include the JSON shown in the log.
Were you able to run the code examples for Java? See eg-03-java-auth-code-grant
Also, please tell us (by editing your question) what you are trying to do.
Creates envelopes - Use Base Url in Api Call
https://demo.docusign.net/restapi/v2.1/accounts/
Error Reason is use Wrong url - https://account-d.docusign.com/restapi/v2.1/accounts/
DocuSign Developers Documentation

Spotify Create Playlist Java - Response Code 400, "Error parsing JSON"

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.

Getting a 400 after setting json parameters

I am trying to send the following json to a REST server from JAVA
{
"image_url":"image",
"job_fqn":"jobfqn",
"ignore_volumes":true
}
I am setting it as follows in my HttpClient
JSONObject json = new JSONObject();
json.put("image_url","image");
json.put("job_fqn","jobfqn");
json.put("ignore_volumes", "true");
StringEntity params = new StringEntity(json.toString());
post.setEntity(params);
HttpResponse response = client.execute(post);
This gives me a 400, after I remove
json.put("ignore_volumes", "true");
this is a valid input , not sure whats going on. The json from curl works fine, only fails in java
Have you tried json.put("ignore_volumes", true);?
Placing the Boolean true instead of the String true.
Try using true as a boolean and not as a string.
json.put("ignore_volumes", true);

Updating multiple fields for an Object - Dynamics CRM 2011 using java

Is there any way to update multiple fields for an object in Dynamics CRM 2011 using java. All I am able to do now is to update one field for an object (ContactSet,AccountSet etc..)
URL : https://xxxxxx.xxxx.xx/xxxxxx/XrmServices/2011/OrganizationData.svc/ContactSet(guid'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')
What I have done?
Map<String,Object> update = Maps.newHashMap();
update.put("FirstName","xxxxx");
update.put("LastName","xxxxx");
update.put("Telephone1","xxxxxxxx");
ObjectMapper mMapper = new ObjectMapper();
mEntity = mMapper.writeValueAsString(update);
String mUrl = this.url+"/"+getObject()+"(guid'"+id+"')";
HttpPut httpPut = new HttpPut(mUrl);
httpPut.setHeader("Content-Type", "application/json");
httpPut.setHeader("Accept","application/json");
httpPut.setEntity(new StringEntity(mEntity,"UTF-8"));
HttpResponse response = this.client.execute(httpPut);
The above code always gives a 500 internal server error.
What works?
Map<String,Object> update = Maps.newHashMap();
update.put("FirstName","xxxxx");
mEntity = mMapper.writeValueAsString(update);
String mUrl = this.url+"/"+getObject()+"(guid'"+id+"')"+"/FirstName";
HttpPut httpPut = new HttpPut(mUrl);
httpPut.setHeader("Content-Type", "application/json");
httpPut.setHeader("Accept","application/json");
httpPut.setEntity(new StringEntity(mEntity,"UTF-8"));
HttpResponse response = this.client.execute(httpPut);
I don't see a point in updating just a single field. Can someone please give pointers on how to update multiple fields?
I would recommend you to use javascript and Jquery or if you prefer java try to follow the microsoft code Javascript example.
It is possible to update multiple columns, just check your code syntax.

Java: Adding raw data to payload Httpost request

I intend to send a simple http post request with a large string in the Payload.
So far I have the following.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("address location");
String cred = "un:pw";
byte[] authEncBytes = Base64.encodeBase64(cred.getBytes());
String authStringEnc = new String(authEncBytes);
httppost.setHeader("Authorization","Basic " + authStringEnc);
However, I do not know how to attach a simple RAW string into the payload. The only examples I can find are name value pairs into the Entity but this is not what I want.
Any assistance?
It depends on the concrete HTTP-API you're using:
Commons HttpClient (old - end of life)
Since HttpClient 3.0 you can specify a RequestEntity for your PostMethod:
httpPost.setRequestEntity(new StringRequestEntity(stringData));
Implementations of RequestEntity for binary data are ByteArrayRequestEntity for byte[], FileRequestEntity which reads the data from a file (since 3.1) and InputStreamRequestEntity, which can read from any input stream.
Before 3.0 you can directly set a String or an InputStream, e.g. a ByteArrayInputStream, as request body:
httpPost.setRequestBody(stringData);
or
httpPost.setRequestBody(new ByteArrayInputStream(byteArray));
This methods are deprecated now.
HTTP components (new)
If you use the newer HTTP components API, the method, class and interface names changed a little bit, but the concept is the same:
httpPost.setEntity(new StringEntity(stringData));
Other Entity implementations: ByteArrayEntity, InputStreamEntity, FileEntity, ...
i was making a common mistake sequence of json object was wrong. for example i was sending it like first_name,email..etc..where as correct sequence was email,first_name
my code
boolean result = false;
HttpClient hc = new DefaultHttpClient();
String message;
HttpPost p = new HttpPost(url);
JSONObject object = new JSONObject();
try {
object.put("updates", updates);
object.put("mobile", mobile);
object.put("last_name", lastname);
object.put("first_name", firstname);
object.put("email", email);
} catch (Exception ex) {
}
try {
message = object.toString();
p.setEntity(new StringEntity(message, "UTF8"));
p.setHeader("Content-type", "application/json");
HttpResponse resp = hc.execute(p);
if (resp != null) {
if (resp.getStatusLine().getStatusCode() == 204)
result = true;
}
Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
return result;
Answer

Categories

Resources