I am trying to send User object to my REST api in json format.
var user={
firstName: "someVal",lastName: "", email: "", contactPhone: "", password: ""
};
var url="http://localhost:8085/MyappName/appliPath/login";
$.ajax({
method:'POST',
contentType: "application/json",
datatype:'json',
url : url,
data:JSON.stringify(user),
success: function(data){
console.log(data);
},
error: function(error){
console.log(error);
}
});
});
Following is my login controller class code
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public static User register(User user){
System.out.println("in register");
User register = null;
if(!validateUser(user.getEmail())){
System.out.println("calling new user");
register = loginDao.addNewUser(user);
System.out.println("returning user");
}
return register;
}
how shall I send complex user to my code? shall I say #Path("{user}") ?
HI You can send complex Object using Post method to your Rest API.
Below is the REST API that will accept the User JOSN object.
You can Follow more about how to post Complex Object here:http://entityclass.in/rest/jerseyClientGetXml.htm
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/StudentService")
public class StudentService {
#POST
#Path("/update")
#Consumes(MediaType.APPLICATION_JSON)
public Response consumeJOSN( User user ) {
User output = user.toString();
return Response.status(200).entity(output).build();
}
}
For this RestFull API i have written JAVA client
public class ClientJerseyPost {
public static void main(String[] args) {
try {
User user = new User();
user.setName("JON");
user.setAddress("Paris");
user.setId(5);
String resturl = "http://localhost:8080/RestJerseyClientXML/rest/StudentService/update";
Client client = Client.create();
WebResource webResource = client.resource(resturl);
ClientResponse response = webResource.accept("application/json")
.post(ClientResponse.class, student);
String output = response.getEntity(String.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
} catch (Exception e) {
}
}
}
Related
Please help, maybe anyone had experience of sending and receiving data through json via a POST request to the server?
There is programming interface (API) to it by passing json data you need to pass the parameters (method, id, params) and get the session ID (result).
Use the library: com.thetransactioncompany.jsonrpc2
The problem is that at the stage of submitting the data (respIn = JSONRPC2Session.send(reqOut) the request falls off with the 500 error, but the server is available, it did not seem to understand that this is a post request, what is my mistake?
NetworkException:
java.io.IOException: Server returned HTTP response code: 500 for URL: https://online.sbis.ru/auth/service/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at com.thetransactioncompany.jsonrpc2.client.RawResponse.parse(Unknown Source)
at com.thetransactioncompany.jsonrpc2.client.JSONRPC2Session.send(Unknown Source)
at ru.documentum.sbis.integration.AuthLink.main(AuthLink.java:115)
Exception in thread "main" java.lang.NullPointerException
at ru.documentum.sbis.integration.AuthLink.main(AuthLink.java:129)
This is my code "main"
package ru.documentum.sbis.integration;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.Proxy;
import com.thetransactioncompany.jsonrpc2.*;
import com.thetransactioncompany.jsonrpc2.client.*;
import java.io.*;
import java.net.*;
import java.util.*;
import sun.rmi.runtime.Log;
import net.minidev.json.JSONAware;
import com.thetransactioncompany.jsonrpc2.JSONRPC2ParseException;
import com.thetransactioncompany.jsonrpc2.client.ConnectionConfigurator;
import com.thetransactioncompany.jsonrpc2.client.RawResponse;
import com.thetransactioncompany.jsonrpc2.client.RawResponseInspector;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Request;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Notification;
public class AuthLink {
public static void main(String[] args) throws IOException {
URL ServerUrl = null;
try
{
ServerUrl = new URL("https://online.sbis.ru/auth/service/");
} catch (MalformedURLException e) {
}
// Create new JSON-RPC 2.0 client session
JSONRPC2Session mySession = new JSONRPC2Session(ServerUrl);
mySession.getOptions().setRequestContentType("application/json-rpc");
mySession.getOptions().acceptCookies(true);
mySession.getOptions().setAllowedResponseContentTypes(new String[]{"application/json-rpc"});
mySession.getOptions().ignoreVersion(true);
mySession.getOptions().parseNonStdAttributes(true);
mySession.getOptions().trustAllCerts(true);
mySession.setConnectionConfigurator(new BasicAuth());
mySession.setRawResponseInspector(new MyInspector());
String method = "СБИС.Аутентифицировать";
Map<String,Object> params = new HashMap<String,Object>();
params.put("Логин", "sc6949");
params.put("Пароль", "!653W74395w");
String id = "0";
System.out.println("Creating new request with properties :");
System.out.println("\tmethod : " + method);
System.out.println("\tparams : " + params);
System.out.println("\tid : " + id + "\n\n");
// Create a new JSON-RPC 2.0 request
JSONRPC2Request reqOut = new JSONRPC2Request(method, params, id);
// Serialise the request to a JSON-encoded string
String json = reqOut.toString();
System.out.println("reqOut - json: Serialised request to JSON-encoded string :");
System.out.println("\t" + json + "\n\n");
JSONRPC2Request reqIn = null;
try
{
reqIn = JSONRPC2Request.parse(json);
} catch (JSONRPC2ParseException e) {
System.out.println(e.getMessage());
return;
}
System.out.println("json - reqIn: Parsed request with properties :");
System.out.println("\tmethod : " + reqIn.getMethod());
System.out.println("\tparams : " + reqIn.getNamedParams());
System.out.println("\tid : " + reqIn.getID() + "\n\n");
String result = "result";
System.out.println("Creating response with properties : ");
System.out.println("\tresult : " + result);
System.out.println("\tid : " + reqIn.getID() + "\n\n"); // ID must be echoed back
// Create response
JSONRPC2Response respOut = new JSONRPC2Response(result, reqIn.getID());
// Serialise response to JSON-encoded string
json = respOut.toString();
System.out.println("Serialised response to JSON-encoded string :");
System.out.println("\t" + json + "\n\n");
// Parse response string
JSONRPC2Response respIn = null;
try {
respIn = mySession.send(reqOut);
} catch ( JSONRPC2SessionException e) {
if (e.getCauseType() == JSONRPC2SessionException.NETWORK_EXCEPTION) {
try {
throw e.getCause();
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if (e.getCauseType() == JSONRPC2SessionException.BAD_RESPONSE) {
}
try {
throw respIn.getError();
} catch (JSONRPC2Error e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
// Check for success or error
if (respIn.indicatesSuccess()) {
System.out.println("getresult The request succeeded :");
System.out.println("\tresult : " + respIn.getResult());
System.out.println("\tid : " + respIn.getID());
}
else {
System.out.println("The request failed :");
JSONRPC2Error err = respIn.getError();
System.out.println("\terror.code : " + err.getCode());
System.out.println("\terror.message : " + err.getMessage());
System.out.println("\terror.data : " + err.getData());
}
}}
This is my code of class "BasicAuth"
package ru.documentum.sbis.integration;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import com.thetransactioncompany.jsonrpc2.client.ConnectionConfigurator;
public class BasicAuth implements ConnectionConfigurator {
public void configure(HttpURLConnection conn) {
conn.setRequestProperty("Host","online.sbis.ru");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty( "charset", "windows-1251");
conn.setRequestProperty("Content-Length", "179");
try {
conn.setRequestMethod("POST");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
}
}
I am currently building an API gateway for a new microservices system, using the Spring Netflix Zuul library.
So far my gateway contains PRE and POST filters that intercept the requests and perform the required logic, etc.
One thing that I see is that REST calls to specific microservices require invoking an API endpoint (either GET or POST) containing JSON payload data that is very complex.
For an end-user sending a request to a microservice containing this JSON would not be user friendly.
I had an idea such that the API gateway act as a mediator, where the user can submit a more "simplified/ user-friendly" JSON to the API gateway, which will transform the JSON payload with the correct "complex" JSON structure that the target microservice can understand in order to handle the request efficiently.
My understanding of how Netflix Zuul is that this can be done by creating a RouteFilter and then including this logic here.
Can anyone explain if (or how) this transformation could be done using Netflix Zuul?
Any advice is appreciated.
Thanks.
No doubt you can do it with Zuul, i am currently trying to do almost the same. i'd suggest you take a look at this repo :
sample-zuul-filters
and the official doc on github.
Filters have to extend ZuulFilter and implement the following methods :
/**
*return a string defining when your filter must execute during zuul's
*lyfecyle ('pre'/'post' routing
**/
#Override
public String filterType(){
return 'pre'; // run this filter before sending the final request
}
/**
* return an int describing the order that the filter should run on,
* (relative to the other filters and the current 'pre' or 'post' context)
**/
#Override
public int filterOrder {
return 1; //this filter runs first in a pre-request context
}
/**
* return a boolean indicating if the filter should run or not
**/
#Override
public boolean shouldFilter() {
RequestContext ctx = RequestContext.getCurrentContext();
if(ctx.getRequest().getRequestURI().equals("/theRouteIWantToFilter"))
{
return true;
}
else {
return false;
}
}
/**
* After all the config stuffs you can set what your filter actually does
* here. This is where your json logic goes.
*/
#Override
public Object run() {
try {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
InputStream stream = ctx.getResponseDataStream();
String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
// transform your json and send it to the api.
ctx.setResponseBody(" Modified body : " + body);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I am not sure my answer is 100% accurate since i am working on it but it's a start.
I've done payload conversion in pre filter but this should work in route filter as well. Use com.netflix.zuul.http.HttpServletRequestWrapper to capture and modify the original request payload before forwarding the request to target microservice.
Sample code:
package com.sample.zuul.filters.pre;
import com.google.common.io.CharStreams;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.http.HttpServletRequestWrapper;
import com.netflix.zuul.http.ServletInputStreamWrapper;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class JsonConverterFilter extends ZuulFilter {
#Override
public String filterType() {
return "pre";
}
#Override
public int filterOrder() {
return 0; // Set it to whatever the order of your filter is
}
#Override
public boolean shouldFilter() {
return true;
}
#Override
public Object run() {
RequestContext context = RequestContext.getCurrentContext();
HttpServletRequest request = new HttpServletRequestWrapper(context.getRequest());
String requestData = null;
JSONParser jsonParser = new JSONParser();
JSONObject requestJson = null;
try {
if (request.getContentLength() > 0) {
requestData = CharStreams.toString(request.getReader());
}
if (requestData == null) {
return null;
}
requestJson = (JSONObject) jsonParser.parse(requestData);
} catch (Exception e) {
//Add your exception handling code here
}
JSONObject modifiedRequest = modifyJSONRequest(requestJson);
final byte[] newRequestDataBytes = modifiedRequest.toJSONString().getBytes();
request = getUpdatedHttpServletRequest(request, newRequestDataBytes);
context.setRequest(request);
return null;
}
private JSONObject modifyJSONRequest(JSONObject requestJSON) {
JSONObject jsonObjectDecryptedPayload = null;
try {
jsonObjectDecryptedPayload = (JSONObject) new JSONParser()
.parse("Your new complex json");
} catch (ParseException e) {
e.printStackTrace();
}
return jsonObjectDecryptedPayload;
}
private HttpServletRequest getUpdatedHttpServletRequest(HttpServletRequest request, final byte[] newRequestDataBytes) {
request = new javax.servlet.http.HttpServletRequestWrapper(request) {
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(
new InputStreamReader(new ByteArrayInputStream(newRequestDataBytes)));
}
#Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStreamWrapper(newRequestDataBytes);
}
/*
* Forcing any calls to HttpServletRequest.getContentLength to return the accurate length of bytes
* from a modified request
*/
#Override
public int getContentLength() {
return newRequestDataBytes.length;
}
};
return request;
}
}
I am calling and displaying a java web service using ASP.NET Web API. How do i make it such that when i run my ASP.NET Web API, the page shows JSON data instead of HTML?
Here are my codes:
DemoRestfulClient.cs
public class DemoRestfulClient
{
private string BASE_URL = "http://localhost:8080/";
public Task<string> AdditionJava2()
{
{
try
{
var client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("AdditionJava2").Result;
return response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
HttpContext.Current.Server.Transfer("ErrorPage.html");
}
return null;
}
}
}
DemoController.cs
public class DemoController : Controller
{
private DemoRestfulClient demoRestfulClient = new DemoRestfulClient();
public ActionResult Index()
{
var Result1 = demoRestfulClient.AdditionJava2().Result;
return Content(Result1);
}
}
Someone please help me. Thank you so much in advance.
public class DemoController : Controller
{
private DemoRestfulClient demoRestfulClient = new DemoRestfulClient();
public ActionResult Index()
{
var Result1 = demoRestfulClient.AdditionJava2().Result;
return Json(Result1);
}
}
The above method will return a json object .
You have wanted to get the json object, right? :)
You have to parse the Json object in order to separately view the content in json.
By using ajax, you can get the content of the json object separately.
For an example,
$.ajax({
url: $("#head").val() + "/Template/updatedTmpltView",
dataType: "html",
data: {},
type: "POST",
success: function (msg) {
data = $.parseJSON(msg)
var name = data.FieldName;
var type = data.FieldType;
var id = data.FieldId;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
In the success (msg), you get the json object as **msg**.
data will include the parsed json object and you can obtain necessary data by data.yourFieldName
Hope this helped you! :)
I have a jersey server. When I attempt to handle a POST from AngularJS (1.2.16), it is generating an error (below). When I use a java jersey client to post the message, the jersey server handles it fine.
SEVERE: null
java.lang.IllegalAccessException: Class com.sun.jersey.server.wadl.generators.WadlGeneratorJAXBGrammarGenerator$8 can not access a member of class javax.ws.rs.core.Response with modifiers "protected"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:101)
at java.lang.Class.newInstance(Class.java:427)
this is the jersey post server:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("/post")
public Response verifyAccount( Owner owner ,
#Context HttpServletRequest req)
{
LOGGER.debug("verify account " +owner.toString() );
HashMap<String, Object> results = new HashMap<String, Object>();
boolean verified = AccountManagement.verifyAccount(owner.getEmail(),
owner.getPwd());
if (verified) {
results.put("status", "OK");
} else {
results.put("status", "Fail");
}
return Response.status(200).entity(results)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
.build();
}
This is the jersey java client:
public class JsonClient {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client
.resource("http://myserver.com:8080/restws/accountcheck/post");
String input = "{\"email\":\"fubar#gmail.com\",\"pwd\":\"hello\"}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
int code = response.getStatus();
if (code != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
System.out.println("exception caught.");
e.printStackTrace();
}
}
}
This is the AngularJS code to post:
$scope.ownerLoginAction = function() {
var dataObject = {
"email": $scope.myId,
"pwd": $scope.mypassword
};
var request = $http({
method: "post",
url: hostName+'/restws/accountcheck/post',
params: {
action:"verify"
},
data: dataObject
});
request.then (function(response) {
console.log(response.data);
},function(errResponse) {
console.error('Error');
} )
}
Anybody know why I cannot seem to post either with JSON from AngularJS? Is the server not set up right? Or the angularJS client is not right?
When i put a TCPMON in between, I noticed that the angularJS attempt sent an OPTION. Is that a clue that I dont understand?
I am trying to use the Google Place Actions API, specifically the events and I cannot get a valid post for the life of me.
Here is the URL I am using:
https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=placesApiKey&duration=26000&reference=CjQwAAAAv4TTQ3ySXiGhOElWFNAQ-roLOfgwo215yRTk1Bmhg0jSJ-sAdz9nHgNgnGBAmqP7EhC7K0AjTfFcZgCUh68c2yNtGhRkmynXvE5d4XA5ZfyBqAxlNdsAIg&summary=this is going to be something fun
The reference is to Tempe, AZ. I keep getting a 404 back saying that it is an illegal request. Any help would be great! I really don't know what I am doing wrong.
I have tried three different ways both with the same results:
HttpClient client = new HttpClient();
client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String url = "https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=" + googlePlacesAPIKey;
PostMethod post = new PostMethod(url);
NameValuePair[] data = {
new NameValuePair("duration", Long.toString(duration)),
new NameValuePair("reference", reference),
new NameValuePair("summary", summary)
};
post.setRequestBody(data);
and
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=" + googlePlacesAPIKey);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("duration", Long.toString(duration)));
nameValuePairs.add(new BasicNameValuePair("reference", reference));
nameValuePairs.add(new BasicNameValuePair("summary", summary));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
}
and
URL url = new URL("https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key="+googlePlacesAPIKey+"&duration="+duration+"&reference="+reference+"&summary="+summary);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter( httpCon.getOutputStream());
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage()); out.close();
and
HttpPost post = new HttpPost("https://maps.googleapis.com/maps/api/place/event/add/json?sensor=false&key=" + googlePlacesAPIKey);
post.setHeader("Content-type", "application/json");
JSONObject object = new JSONObject();
object.put("duration", Long.toString(duration));
object.put("reference", reference);
object.put("summary", summary);
String message = object.toString();
post.setEntity(new StringEntity(message));
HttpResponse response = client.execute(post);
Here is the link to the API for those that are curious:
https://developers.google.com/places/documentation/actions#event_add
In python, you can do like this:
#!/usr/bin/python
# coding: utf8
import sys
import urllib
parameters = urllib.urlencode({
'key' : "YOUR_API_KEY",
'sensor' : 'false'
})
url = "https://maps.googleapis.com/maps/api/place/event/add/json?%s" % (parameters)
#The reference
reference = "CoQBdgAAAN4u...YKmgQ"
#Add event
postdata = '''
{
"duration": 86400,
"language": "ja",
"reference": "%s",
"summary": "Event Name!",
"url" : "http://hogehoge.com/test_page"
}
''' % (reference)
f = urllib.urlopen(url, postdata)
print f.read()
Ok, I'm not good for Java though, I created an example code for Android Java.
[MainActivity.java]
package com.example.placeseventtest;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private final String API_KEY = "YOUR_API_KEY";
private PlacesHTTP myUtil;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView resTxtView = (TextView) findViewById(R.id.responseText);
myUtil = new PlacesHTTP(API_KEY, resTxtView);
Button currentPosBtn = (Button) this.findViewById(R.id.currentPosBtn);
currentPosBtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
JSONObject params = new JSONObject();
JSONObject location = new JSONObject();
JSONArray types = new JSONArray();
try {
location.put("lat", 123.4556);
location.put("lng", 123.4556);
params.put("location", location);
params.put("accuracy", 20);
params.put("name", "Event Name");
//only one type is available.
types.put("parking");
params.put("types", types);
params.put("language", "en");
} catch (Exception e) {}
// Show the request JSON data.
TextView reqTxtView = (TextView) findViewById(R.id.requestText);
try {
reqTxtView.setText(params.toString(2));
} catch (Exception e) {}
// POST to Google Server
myUtil.execute(params);
}
});
}
}
[PlacesHTTP.java]
package com.example.placeseventtest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.widget.TextView;
public class PlacesHTTP extends AsyncTask<JSONObject, Void, HttpResponse>{
private HttpPost post;
private HttpClient httpClient;
private String url;
private TextView txtView;
public PlacesHTTP(String api_key, TextView resultView) {
url = String.format("https://maps.googleapis.com/maps/api/place/add/json?sensor=false&key=%s", api_key);
txtView = resultView;
}
protected void onPreExecute() {
httpClient = new DefaultHttpClient();
post = new HttpPost(url);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
}
#Override
protected HttpResponse doInBackground(JSONObject... params) {
//Send data as JSON format
JSONObject opts = params[0];
StringEntity strEntity;
HttpResponse response = null;
try {
strEntity = new StringEntity(opts.toString());
post.setEntity(strEntity);
response = httpClient.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(HttpResponse result) {
if (result != null) {
// Display the result
try {
txtView.setText(EntityUtils.toString(result.getEntity()));
} catch (Exception e) {
e.printStackTrace();
}
} else {
txtView.setText("null");
}
}
}
I got this result: