Not getting JSON value in Spring Controller method - java

I need to send some data from my Android device to my server. I am doing this through JSON. I have implemented the JSON post on Android, and I am trying to do a mapping on the server side in order to retrieve that data. My problem is that I keep getting an empty string.
Android method used to send JSON:
private void sendJson(final String json, final String URL) {
Thread t = new Thread(){
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
try{
HttpPost post = new HttpPost(URL);
StringEntity se = new StringEntity(json);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
client.execute(post);
}
catch(Exception e){
e.printStackTrace();
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
Server-side method:
#RequestMapping(value = "/getLatestCalls", method = RequestMethod.POST)
public void getData(#ModelAttribute String json){
//... do something
}
The thing is that in this method my json String is "" every time. I have also tried using #RequestParam but with that it doesn't enter the method anymore. I have also tried with #ModelAttribute("json").
Can someone enlighten me a little here? Thank you in advance.

Here is the solution and it works fine.
server-side
#Controller
public class DataCollector {
#RequestMapping(value = "/clientdatacollector", method = RequestMethod.POST)
public #ResponseBody
void abc(Writer writer, #RequestParam("gpsdata") String gpsJSON) {
try {
// here is your jsonstring ;)
writer.write(gpsJSON.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
client-side
public static void httptest() {
ArrayList<TravellingData> tdArray = new ArrayList<TravellingData>();
Gson gson = new Gson();
String jsonString = "";
for (int i = 0; i < 1; i++) {
tdArray.add(ObjectCreater.createMockTravellingDataObject());
}
jsonString = gson.toJson(tdArray);
HttpClient client = new DefaultHttpClient();
HttpPost post = null;
try {
post = new HttpPost(
"http://localhost:8080/uygulama/clientdatacollector");
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("gpsdata", jsonString));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = null;
try {
response = client.execute(post);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}

Try using #RequestBody. It should work.

Related

Android send json to Spring

Spring Controller
#RequestMapping(value = "/login", produces="application/json;charset=UTF-8" ,method = RequestMethod.POST)
#ResponseBody
public int checkLoginInfo(#RequestParam Map<String, String> params) {
User user=new Gson().fromJson((String) params.get("user"), User.class);
return userService.getUserInfo(user);
}
HTML
var params={userid:$("#userid").val(),password:$("#password").val()}
$ajax({method:"post",data:{user:JSON.stringify(params)},url:"foo.bar"});
It worked on website.
But I don't know how to send that Json object for android.
data:{user:JSON.stringify(params)}
I have tested
private static String makeJsonMsg() {
String retMsg = "";
JSONStringer jsonStringer = new JSONStringer();
try {
retMsg = jsonStringer.object()
.key("user").object()
.key("userid").value("userid")
.key("password").value("1234")
.endObject()
.endObject().toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retMsg;
}
like that,
But return 500 error.
Do I need to add header or something else?
The simple way
public void postData(String url,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams );
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(url.toString());
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
How to use
JSONObject requestObject = new JSONObject();
requestObject.put("userid", email);
requestObject.put("password", password);
postData("http://your/login/url",requestObject)
For more info check How to send a JSON object over Request with Android?. Credit of the postData method is for #Sachin Gurnani answer
Hope this helps!!

Is this correct approach to submitting JSON via HTTP POST to a java Web Server?

I construct the JSON Object
JSONObject jsonobj = new JSONObject();
JSONObject geoJsonObj = new JSONObject();
try {
jsonobj.put("action","put-point");
geoJsonObj.put("lng", longitude);
geoJsonObj.put("lat", latitude);
geoJsonObj.put("rangeKey", rangeKey);
geoJsonObj.put("schoolName", "TESTSCHOOL535353");
jsonobj.put("request", geoJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
I Execute an AsyncTask
new HTTPtoServer().execute(jsonobj);
The AsyncTask looks like this:
private class HTTPtoServer extends AsyncTask<JSONObject, Void, String> {
#Override
protected String doInBackground(JSONObject... params) {
//Prepare HTTP Post Client
DefaultHttpClient myClient = new DefaultHttpClient();
HttpPost myPost = new HttpPost(ElasticBeanStalkEndpoint);
StringEntity se = null;
Log.v("TEST","TEST");
try {
se = new StringEntity(params[0].toString());
Log.v("MY SE", se.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
myPost.setEntity(se);
HttpResponse httpresponse = null;
try {
httpresponse = myClient.execute(myPost);
} catch (IOException e) {
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(httpresponse.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
return responseText;
}
#Override
protected void onPostExecute(String s) {
Log.v("MY STRING", s);
}
}
However my JSON Object appears to never be "sending"?
Or maybe it is, but in an incorrect format?
The Java Tomcat server doesn't seem to be doing anything with the data?
My StringEntity results in :
org.apache.http.entity.StringEntity#528111f8
When I do se.toString()... Is this correct?
I seem to be a bit confused.
SERVER CODE:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
try {
StringBuffer buffer = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
JSONObject jsonObject = new JSONObject(buffer.toString());
PrintWriter out = response.getWriter();
String action = jsonObject.getString("action");
log("action: " + action);
JSONObject requestObject = jsonObject.getJSONObject("request");
log("requestObject: " + requestObject);
if (action.equalsIgnoreCase("put-point")) {
putPoint(requestObject, out);
} else if (action.equalsIgnoreCase("get-point")) {
getPoint(requestObject, out);
} else if (action.equalsIgnoreCase("update-point")) {
updatePoint(requestObject, out);
} else if (action.equalsIgnoreCase("query-rectangle")) {
queryRectangle(requestObject, out);
} else if (action.equalsIgnoreCase("query-radius")) {
queryRadius(requestObject, out);
} else if (action.equalsIgnoreCase("delete-point")) {
deletePoint(requestObject, out);
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
log(sw.toString());
}
}
private void putPoint(JSONObject requestObject, PrintWriter out) throws IOException, JSONException {
GeoPoint geoPoint = new GeoPoint(requestObject.getDouble("lat"), requestObject.getDouble("lng"));
AttributeValue rangeKeyAttributeValue = new AttributeValue().withS(UUID.randomUUID().toString());
AttributeValue schoolNameKeyAttributeValue = new AttributeValue().withS(requestObject.getString("schoolName"));
PutPointRequest putPointRequest = new PutPointRequest(geoPoint, rangeKeyAttributeValue);
putPointRequest.getPutItemRequest().addItemEntry("schoolName", schoolNameKeyAttributeValue);
PutPointResult putPointResult = geoDataManager.putPoint(putPointRequest);
printPutPointResult(putPointResult, out);
}
Try like that.
JSONObject jsonobj = new JSONObject();
JSONObject geoJsonObj = new JSONObject();
try {
jsonobj.put("action","put-point");
geoJsonObj.put("lng", longitude);
geoJsonObj.put("lat", latitude);
geoJsonObj.put("rangeKey", rangeKey);
geoJsonObj.put("schoolName", "TESTSCHOOL535353");
jsonobj.put("request", geoJsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
new SendData().execute(jsonobj.toString());
public class SendData extends AsyncTask<String, Integer, Double>{
String response="";
#Override
protected Double doInBackground(String... params) {
postData(params[0]);
}
public void postData(String jsondata) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost=new HttpPost("url");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json",jsondata));
httpPost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse res = httpclient.execute(httpPost);
InputStream content = res.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
System.out.println("response from server"+response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
SERVER SIDE-
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String jsondata=request.getParameter("json");
//now parse your data from json
try {
JSONObject JsonObject=new JSONObject(jsondata);
JSONObject object=JsonObject.getJSONObject("request");
String action=object.getString("action");
String lng=object.getString("lng");
String lat=object.getString("lat");
String rangeKey=object.getString("rangeKey");
String schoolName=object.getString("schoolName");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I hope this will help you...!
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(PROJECT_ID, params[0]));
nameValuePairs.add(new BasicNameValuePair(BROKER_ID,params[1]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
StringBuilder responseJsonStr = new StringBuilder();
while ((output = br.readLine()) != null) {
responseJsonStr.append(output);
}
String queryString = Utils.getQueryString(nameValuePairs);
System.out.println("Query String "+URL +"&"+queryString);
//System.out.println("response Json String "+responseJsonStr );
if(!StringUtils.startsWith(responseJsonStr.toString(), "[")) {
responseJsonStr.insert(0,"[");
responseJsonStr.append("]");
}
try this:
public String getJson(Context applicationContext,String url) {
InputStream is = null;
String result = "";
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("response_key",PrefernceSettings.getRestKey()));
nameValuePair.add(new BasicNameValuePair("response_request","auto_payments"));
Log.e("",String.valueOf(nameValuePairs));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
if(is != null){
result = convertInputStreamToString(is);
Log.e("result", result);
}else{
result = "Did not work!";
}
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
public String convertInputStreamToString(InputStream inputStream) {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
try {
while((line = bufferedReader.readLine()) != null)
result += line;
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
Try using this function:
public boolean postJSON(JSONObject jsonobj) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost("YOUR URL HERE");
StringEntity se = new StringEntity(jsonobj.toString());
// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
httpPostRequest.setHeader("Accept-Encoding", "gzip");
//Send Http request
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
HttpEntity entity = response.getEntity();
String resonseStr = EntityUtils.toString(entity);
return getResponse(resonseStr);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
0D
where getResponse is a function that gets the response string and parses it and returns true or false according to how you define the web service.

How do you get content from a HttpResponse in servlet?

I am currently learning to develop android application. I need to parse variables from my android application to the servlet. I use HttpResponse to parse the variables. But i do not know how to accept parameters in servlet.
This is my code in android application.
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://<ip_address>:8080/GetPhoneNumber/GetPhoneNumberServletServlet");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("phoneNum", "12345678"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} // End of onClick method
May I know what to do at the doPost/doGet in servlet?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
out.println("Hello Android !!!!");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
In your doPost use request.getParameter("phoneNum").
I think the following code could help you.
public class CustomHttpClient
{
public static final int HTTP_TIMEOUT = 30 * 1000;
private static HttpClient mHttpClient;
private static HttpClient getHttpClient()
{
if (mHttpClient == null)
{
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url,ArrayList<NameValuePair> postParameters) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
public static String executeHttpGet(String url) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
}
Addons:-
Use the JSON Parser class below:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("json data",json.toString());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Now if you want to send anything on the server, say you need to save the username and password on the server using the JSON Parser and PHP use the below code in any thread or in the doInBackground method of Async task.
ArrayList<NameValuePair> Insert = new ArrayList<NameValuePair>();
Insert.add(new BasicNameValuePair("User_Name","<Sting denoting username>"));
Insert.add(new BasicNameValuePair("Password","<Sting denoting Password>));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://server path/yourphpfile.php");
httppost.setEntity(new UrlEncodedFormEntity(Insert));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}
Now if you need these values back using the get method in JSON Parser, user the following code again in the Thread or doInBackground method of Async task.
public class CountDownTask extends AsyncTask<Void,Void , Void>
{
protected void onPreExecute()
{
count = 0;
S_Store_Id = null; S_Store_Name = null;S_Store_Address = null; S_Store_Phone= null;
Offers = null; Descriptions = null;
}
protected Void doInBackground(Void... params)
{
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("User_Name",StringUserName));
String response = null;
try
{
response = CustomHttpClient.executeHttpPost("http://yourserverpath/yourphpfilefor retrivingdata.php",postParameters);
String result = response.toString();
try
{
JSONArray jArray = new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(0);
StringUserName = json_data.getString("User_Name");
StringPassword = json_data.getString("Password");
json_data = jArray.getJSONObject(1);
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
catch (Exception e)
{
Log.e("log_tag","Error in http connection!!" + e.toString());
}
return null;
}
Now you can write the logic for inserting and retriving data from the server in your corresponding PHP files and use them for using data from the server. This method works equivalent to HTTP Get and Post methods of HTTP Request and Response.
Hope it can help you.. Thanks...

android.os.networkonmainthreadexception error in my request response class for JSON

How should I use my aux class for JSON request, bcoz in android 2,3 work but android 4.x dont work
I read that I need to use Asyntask for fix it, or create thread, I prefer Asyntask but I cant compile it.
How fix my code for asyntask ?
public class Httppostaux {
InputStream is = null;
String result = "";
public JSONArray getserverdata(ArrayList<NameValuePair> parameters, String urlwebserver ){
//conecta via http y envia un post.
httppostconnect(parameters,urlwebserver);
if (is!=null){//si obtuvo una respuesta
getpostresponse();
return getjsonarray();
}else{
return null;
}
}
//peticion HTTP
private void httppostconnect(ArrayList<NameValuePair> parametros, String urlwebserver){
//
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlwebserver);
httppost.setEntity(new UrlEncodedFormEntity(parametros));
//ejecuto peticion enviando datos por POST
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error en la conexión HTTP "+e.toString());
}
}
public void getpostresponse(){
//Convierte respuesta a String
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.e("getpostresponse"," result= "+sb.toString());
}catch(Exception e){
Log.e("log_tag", "Error conviertiendo el resultado "+e.toString());
}
}
public JSONArray getjsonarray(){
//parse json data
try{
JSONArray jArray = new JSONArray(result);
return jArray;
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
return null;
}}}
You should not perform network operations on main thread 4.0 and above. Read this to know how to perform network operations correctly https://developer.android.com/training/basics/network-ops/connecting.html
Here i put the sample code for how i use Asyc task for api calling, hope it will help for you and modify this code as per your need,
new Read().execute(); // Asyc Task initialization
public class Read extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
json = lastTweet(); // url executed here and the final value is stored in json obj
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// Here you call the json obj and do your UI binding.
}
}
public JSONObject lastTweet() throws ClientProtocolException, IOException,
JSONException {
HttpClient client = new DefaultHttpClient();
StringBuilder url = new StringBuilder(<your_URL>);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
Log.e("RESPONSE VALUE IS", data); // Here you get the response
JSONObject last = new JSONObject(data);
return last; //here the response value is returned
} else {
Toast.makeText(getBaseContext(), "error", Toast.LENGTH_SHORT);
return null;
}
}
In your manifest.xml don't forget to add this permission <uses-permission android:name="android.permission.INTERNET" />

IOException: Internal Server Error when trying to consume rest service

I want to create a restful web service in java using jersey API and consume it in android application. I got this question on SO but it talks about java client whereas I have android client.
My service looks like this:
#Path("/no")
public class CheckNumber {
#POST
#Produces("application/json")
#Consumes("application/json")
public String getDetails(#PathParam("cNo") String cNo) {
String CardNo="";
try {
JSONObject jsonObj = new JSONObject(cNo);
CardNo=jsonObj.getString("CardNo");
} catch (ParseException e1) {
e1.printStackTrace();
}
//Do something
return "someValue";
}
}
Now comes the client side:
public class MainActivity extends Activity {
JSONObject json = new JSONObject();
String wsdl = "http://192.168.1.105:8080/restdemo/check/no/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new RequestTask().execute("1234567890");
}
class RequestTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String add = "{\"CardNo\":\"" + uri[0] + "\"}";
HttpPost postMethod = new HttpPost(wsdl);
String responseString = null;
try {
postMethod.addHeader("Content-Type", "application/json");
HttpEntity entity = new StringEntity(add);
postMethod.setEntity(entity);
response = httpclient.execute(postMethod);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
}
I'm just starting with rest web services. I successfully created a sample rest service which consumes string and returns string and used this service in android app.
But when I try to pass json string using POST method. It's giving following errorin log:
java.io.IOException: Internal Server Error
at com.example.restclient.MainActivity$RequestTask.doInBackground(MainActivity.java:85)
where MainActivity.java:85 is throw new IOException(statusLine.getReasonPhrase()); which implies that statusLine.getStatusCode() is not returning HttpStatus.SC_OK. Instead it's returning status code = 500.
Any help appreciated.
It will be good to see the server side log to understand better.
Try creating the entity with UTF8 and set the content-type in the string entity rather than in the postMethod
StringEntity stringEntity = new StringEntity(myJsonDocStr, HTTP.UTF_8);
stringEntity.setContentType("application/json");
Try this code, It works for me
Boolean NetworkLostFlag = false;
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 10000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 12000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(strUrl");
try {
httppost.setEntity(new UrlEncodedFormEntity(new BasicNameValuePair(arg1, val1), "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
// do something useful
StringBuffer buffer = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = instream.read(b)) != -1;) {
buffer.append(new String(b, 0, n));
}
result = buffer.toString();
} catch (Exception e) {
NetworkLostFlag = true;
// TODO: handle exception
} finally {
instream.close();
}
}
} catch (Exception e) {
NetworkLostFlag = true;
e.printStackTrace();
}

Categories