开发者

how to Post data in certain format in android

Suppose user enter the 10 digit number in edit text for example 1234567890 .

public class main extends Activity {

    EditText number;
    @override
    public void onCreate(Bundle savedInstanceState) {
        super.on开发者_如何学编程Create(savedInstanceState);
        setContentView(R.layout.main);
        number=(EditText)findviewbyid(R.id.munber);

        String pno=number.getText().toString();

Now I have to send (http Post) this number in (123)456-7890 format to server side on submit click. How can I achieve this?

If you have an example then share with me.


A quick and dirty way to reformat the string is

String pno=number.getText().toString();
String hpno = "(" + pno.substring(0,3) + ")" + pno.substring(3,6) + "-"+pno.substring(6, pno.length());

and then you can post that.


The simplest method I know of is using the HttpClient library:

public static String postRequest(String uri) throws Exception {
    BufferedReader in;
    StringBuffer sb = new StringBuffer("Error: Could not connect to host");
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost();
        post.setURI(new URI(uri);
        HttpResponse response = client.execute(post);
        in = new BufferedReader
        (new InputStreamReader(response.getEntity().getContent()));
        sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
    }catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

That will perform a post and return the response to your client. Works well for me for a simple REST CRUD application.

ref: here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜