Android - 发布到 RESTful Web 服务

标签 android rest post

我正在寻找有关如何在我的 Android 应用程序中将数据发布到 Web 服务的指南。不幸的是,这是一个学校项目,所以我无法使用外部库。

Web 服务有一个基本 URL,例如:

http://example.com/service/create

并接受两个变量,格式如下:

username = "user1"
locationname = "location1"

Web 服务是 RESTful 的,并且使用 XML 结构,如果这有所不同的话。根据我的研究,我知道我应该使用 URLconnection 而不是已弃用的 HTTPconnection,但我找不到我正在寻找的示例。

这是我的尝试,目前无法正常工作:

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toPost test = new toPost();
        text.execute();
    }

    private class toPost extends AsyncTask<URL, Void, String> {
        @Override
        protected String doInBackground(URL... params) {
            HttpURLConnection conn = null;
            try {
                URL url = new URL("http://example.com/service");
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                String body = "username=user1&locationname=location1";
                OutputStream output = new BufferedOutputStream(conn.getOutputStream());
                output.write(body.getBytes());
                output.flush();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                conn.disconnect();
            }
            return null;
        }
    }

}

最佳答案

我会使用 volley 库,as suggested by google

在那个页面上解释了如何发出请求,但是非常简单:

final TextView mTextView = (TextView) findViewById(R.id.text);
...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

关于Android - 发布到 RESTful Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33746655/

相关文章:

ruby-on-rails - 服务到服务认证、服务身份和访问权限管理

php - 光谱颜色选择器将 id 和颜色发送到 php

c - 如何使用 http post 传输 tar.gz 文件?

android - YouTube 嵌入式视频在 Android 上单击“播放”按钮时显示开发人员选项

rest - 为什么 Elasticsearch 批量插入使用\n定界符,而不是使用json对象数组?

android - 检查数据连接是否为 "ticked"

java - Spring REST MultipartFile 文件始终为空

javascript - $.post函数可以覆盖父函数中的变量吗

android - 从 xml 文件调用颜色

java - 回收者 View 混合了其元素的内容