7

How would I send a string data (JSONObject.toString()) to a url. I want to write a static method in a util class to do this. I want the method signature to be as follows

public static String postData (String url, String postData) throws SomeCustomException

What should be the format of the string url

The return String is the response from the server in as a string representation of json data.

EDIT

Present connection util

package my.package;
import my.package.exceptions.CustomException;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;


 public class ConnectionUtil {

 public static String postData(String url, String postData)
        throws CustomException {

    // Create a new HttpClient and Post Header
    InputStream is = null;
    StringBuilder sb = null;
    String result = "";
    HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost();
    httppost.setHeader("host", url);

    Log.v("ConnectionUtil", "Opening POST connection to URI = " + httppost.getURI() + " url = " + URLDecoder.decode(url));

    try {
        httppost.setEntity(new StringEntity(postData));

        // Execute HTTP Post Request
        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());
        e.printStackTrace();
        throw new CustomException("Could not establish network connection");
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        String line = "0";

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        is.close();
        result = sb.toString();

    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
        throw new CustomException("Error parsing the response");
    }
    Log.v("ConnectionUtil", "Sent: "+postData);
    Log.v("ConnectionUtil", "Got result "+result);
    return result;

}

}

Logcat output

10-16 11:27:27.287: E/log_tag(4935): Error in http connection java.lang.NullPointerException 10-16 11:27:27.287: W/System.err(4935): java.lang.NullPointerException 10-16 11:27:27.287: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:496) 10-16 11:27:27.307: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 10-16 11:27:27.327: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ConnectionUtil.postData(ConnectionUtil.java:92) 10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:54) 10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:1) 10-16 11:27:27.327: W/System.err(4935): at android.os.AsyncTask$2.call(AsyncTask.java:185) 10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.FutureTask.run(FutureTask.java:138) 10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 10-16 11:27:27.327: W/System.err(4935): at java.lang.Thread.run(Thread.java:1019) 10-16 11:27:27.327: V/log_tag(4935): Could not establish network connection
1
  • I think there is some problem with your POST method sending StringEntity to the server end.. Check out my latest answer and see if it works.. Commented Oct 16, 2012 at 6:41

4 Answers 4

2

I think in your code the basic problem is caused by the way you are using StringEntity to POST parameters to your url. Check to see if the following code helps in posting your data to the server using StringEntity.

    // Build the JSON object to pass parameters
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("username", username);
    jsonObj.put("data", dataValue);

    // Create the POST object and add the parameters
    HttpPost httpPost = new HttpPost(url);
    StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
    entity.setContentType("application/json");
    httpPost.setEntity(entity);

    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(httpPost);

Hope this helps in solving your problem. Thanks.

2
  • Hi. I think this helped but I am still getting an runtime error UnknownHostException. I am sure my url works and checked from my browser. I also get the same error for google.com or example.com. How should I format the URL/URI? I want to hit the URL http://xyz.mysite.com/some_page.php/ and post data. Do I need to also specify the port?
    – kapad
    Commented Oct 16, 2012 at 7:11
  • Just using 80. So that should be default. This is now working and hitting the server. Thank you.
    – kapad
    Commented Oct 16, 2012 at 8:52
2

Well, here are my thoughts on your question:-

  1. First, you should simply send the data to the server by using POST method. Its easy and absolutely possible in Android also. A simple code snippet for sending POST data can be like:

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "http://yourserverIP/postdata.php");
    String serverResponse = null;
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("datakey1", dataValue1));
        nameValuePairs.add(new BasicNameValuePair("datakey2",
                dataValue2));
    
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
    
        serverResponse = response.getStatusLine().toString();
        Log.e("response", serverResponse);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    The above code sends data to a PHP script postdata on your server.

  2. Next, for parsing the JSON data sent by the server, you can use a JSONParser and then easily utilize it as per your needs. You can get the response returned from the server by using the following code:

    String jsonData = EntityUtils.toString(serverResponse.getEntity());
    

Hope this helps. Thanks.

4
  • I am not using a form. the server just wants to see string data. thats all.
    – kapad
    Commented Oct 16, 2012 at 5:19
  • @phodu_insaan Even for sending string data, you will need to send POST data to the server. So, you don't need to be using a form for sending string data to the server. And if you simply just want to send commands like passing just one parameter to the server, then you may also think about using GET method. I can help you with GET too. Commented Oct 16, 2012 at 5:24
  • I am doing almost the same thing. Instead of passing a UrlEncodedFormEntity I am passing a new StringEntity with my String data. I get a NullPointerException. Just appending my logcat output to the question.
    – kapad
    Commented Oct 16, 2012 at 6:05
  • Yes, plz add your LogCat output here.. And I am not able to get you, how are you passing a StringEntity?? Please add your code also that is performing this task.. That will help in understanding your problem in a better way.. Commented Oct 16, 2012 at 6:07
1

try using this method where strJsonRequest is the json string you want to post and the strUrl is the url to which you want to post the strJsonRequest

   public String urlPost(String strJsonRequest, String strURL) throws Exception 
{
    try
    {
        URL objURL = new URL(strURL);
        connection = (HttpURLConnection)objURL.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setAllowUserInteraction(false);
        connection.setUseCaches(false);
        connection.setConnectTimeout(TIMEOUT_CONNECT_MILLIS);
        connection.setReadTimeout(TIMEOUT_READ_MILLIS);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept-Charset", "utf-8");
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.setRequestProperty("Content-Length", ""+strJsonRequest.toString().getBytes("UTF8").length);

        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        byte [] b = strJsonRequest.getBytes("UTF-8");

        outputStream.write(b);
        outputStream.flush();

        inputstreamObj = (InputStream) connection.getContent();//getInputStream();

        if(inputstreamObj != null)
            strResponse = convertStreamToString(inputstreamObj);

    }
    catch(Exception e)
    {
        throw e;
    }
    return strResponse;
}

and the method convertStreamToString() is as below

private static String convertStreamToString(InputStream is)
{
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is));
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    StringBuilder sb = new StringBuilder();

    String line = null;
    try
    {
        while ((line = reader.readLine()) != null) 
        {
            sb.append(line + "\n");
        }
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
    finally 
    {
        try 
        {
            is.close();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
3
  • what is the method converStreamToString?
    – kapad
    Commented Oct 16, 2012 at 5:07
  • what should be the url format? I am getting a MalformedURLException
    – kapad
    Commented Oct 16, 2012 at 5:50
  • am not sure what is the url that you are getting in the logcat once check whether its the same that you passed
    – G_S
    Commented Oct 16, 2012 at 5:58
0

Depending on how your server side code is set up, an example format of the url where your server has a php page to handle the API call would be:

http://yoururl.com/demo.php?jsondata=postData

If your are using a post connection you can simply say:

http://yoururl.com/demo.php

and pass it your post parameters i.e. the json string

Here is a great tutorial on how to do this: http://yoururl.com/demo.php?jsondata=postData

1
  • the server accepts a post connection. So I just need the url like http://www.example.com/my_page.php, right?
    – kapad
    Commented Oct 16, 2012 at 5:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.