Android-发布到RESTful Web服务

Android-发布到RESTful Web服务,android,rest,post,Android,Rest,Post,我正在寻找一些关于如何在我的Android应用程序中将数据发布到web服务的指导。不幸的是,这是一个学校项目,所以我不能使用外部图书馆 web服务有一个基本URL,例如: http://example.com/service/create import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import java.io.BufferedO

我正在寻找一些关于如何在我的Android应用程序中将数据发布到web服务的指导。不幸的是,这是一个学校项目,所以我不能使用外部图书馆

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

http://example.com/service/create
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();
        test.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();

                //This is needed
                // Could alternatively use conn.getResponseMessage() or conn.getInputStream()
                conn.getResponseCode();

            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                conn.disconnect();
            }
            return null;
        }
    }
}
并采用以下格式的两个变量:

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;
        }
    }

}
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.support.v7.app.AppActivity;
导入java.io.BufferedOutputStream;
导入java.io.IOException;
导入java.io.OutputStream;
导入java.net.HttpURLConnection;
导入java.net.ProtocolException;
导入java.net.URL;
公共类MainActivity扩展了AppCompatActivity{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toPost测试=新的toPost();
text.execute();
}
私有类toPost扩展异步任务{
@凌驾
受保护的字符串doInBackground(URL…参数){
HttpURLConnection conn=null;
试一试{
URL=新URL(“http://example.com/service");
conn=(HttpURLConnection)url.openConnection();
连接设置读取超时(10000);
连接设置连接超时(15000);
conn.setRequestMethod(“POST”);
conn.setDoInput(真);
连接设置输出(真);
String body=“username=user1&locationname=location1”;
OutputStream输出=新的BufferedOutputStream(conn.getOutputStream());
output.write(body.getBytes());
output.flush();
}捕获(协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}最后{
连接断开();
}
返回null;
}
}
}

是的,您应该使用URLConnection进行请求

您可以将xml数据作为有效负载发送

请参阅

URL=newurl(URL);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
试一试{
连接设置读取超时(10000);
连接设置连接超时(15000);
conn.setRequestMethod(“POST”);
conn.setDoInput(真);
连接设置输出(真);
String body=“我的建议是在与之间使用

改型支持异步和同步请求。它支持
GET
POST
PUT
DELETE
HEAD
方法

Jackson将帮助您将XML解析为JSON对象

这两个都非常容易使用,并且有很好的文档


您可以找到使用改装的简单教程。

我会使用volley库

提出请求在该页上有说明,但很简单:

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);
final TextView mTextView=(TextView)findviewbyd(R.id.text);
...
//实例化RequestQueue。
RequestQueue=Volley.newRequestQueue(this);
字符串url=”http://www.google.com";
//从提供的URL请求字符串响应。
StringRequest StringRequest=新的StringRequest(Request.Method.GET,url,
新的Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
//显示响应字符串的前500个字符。
mTextView.setText(“响应为:”+Response.substring(0500));
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
setText(“那没用!”);
}
});
//将请求添加到RequestQueue。
添加(stringRequest);

如果您想使用HttpUrlConnection,可以参考以下两个示例。希望这对您有所帮助

private class LoginRequest extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... voids) {
        String address = "http://server/login";
        HttpURLConnection urlConnection;
        String requestBody;
        Uri.Builder builder = new Uri.Builder();
        Map<String, String> params = new HashMap<>();            
        params.put("username", "bnk");
        params.put("password", "bnk123");

        // encode parameters
        Iterator entries = params.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
            entries.remove();
        }
        requestBody = builder.build().getEncodedQuery();

        try {
            URL url = new URL(address);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
            writer.write(requestBody);
            writer.flush();
            writer.close();
            outputStream.close();

            JSONObject jsonObject = new JSONObject();
            InputStream inputStream;
            // get stream
            if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                inputStream = urlConnection.getInputStream();
            } else {
                inputStream = urlConnection.getErrorStream();
            }
            // parse stream
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String temp, response = "";
            while ((temp = bufferedReader.readLine()) != null) {
                response += temp;
            }
            // put into JSONObject
            jsonObject.put("Content", response);
            jsonObject.put("Message", urlConnection.getResponseMessage());
            jsonObject.put("Length", urlConnection.getContentLength());
            jsonObject.put("Type", urlConnection.getContentType());

            return jsonObject.toString();
        } catch (IOException | JSONException e) {
            return e.toString();
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.i(LOG_TAG, "POST\n" + result);
    }
}


private class JsonPostRequest extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... voids) {
        try {
            String address = "http://server/postvalue";
            JSONObject json = new JSONObject();                
            json.put("Title", "Dummy Title");
            json.put("Author", "Dummy Author");
            String requestBody = json.toString();
            URL url = new URL(address);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
            writer.write(requestBody);
            writer.flush();
            writer.close();
            outputStream.close();

            InputStream inputStream;
            // get stream
            if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                inputStream = urlConnection.getInputStream();
            } else {
                inputStream = urlConnection.getErrorStream();
            }
            // parse stream
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String temp, response = "";
            while ((temp = bufferedReader.readLine()) != null) {
                response += temp;
            }
            // put into JSONObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Content", response);
            jsonObject.put("Message", urlConnection.getResponseMessage());
            jsonObject.put("Length", urlConnection.getContentLength());
            jsonObject.put("Type", urlConnection.getContentType());
            return jsonObject.toString();
        } catch (IOException | JSONException e) {
            return e.toString();
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.i(LOG_TAG, "POST RESPONSE: " + result);
        mTextView.setText(result);
    }
}
私有类LoginRequest扩展了异步任务{
@凌驾
受保护的字符串背景(无效…无效){
字符串地址=”http://server/login";
HttpURLConnection-urlConnection;
字符串请求体;
Uri.Builder=新的Uri.Builder();
Map params=新的HashMap();
参数put(“用户名”、“bnk”);
参数put(“密码”、“bnk123”);
//编码参数
迭代器条目=params.entrySet().Iterator();
while(entries.hasNext()){
Map.Entry=(Map.Entry)entries.next();
builder.appendQueryParameter(entry.getKey().toString(),entry.getValue().toString());
条目。删除();
}
requestBody=builder.build().getEncodedQuery();
试一试{
URL=新的URL(地址);
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setDoOutput(true);
setRequestProperty(“内容类型”,“应用程序/x-www-form-urlencoded”);
OutputStream OutputStream=新的BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer=新的BufferedWriter(新的OutputStreamWriter(outputStream,utf-8));
writer.write(请求体);
writer.flush();
writer.close();
outputStream.close();
JSONObject JSONObject=新的JSONObject();
输入流输入流;
//获取流
if(urlConnection.getResponseCode()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();
        test.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();

                //This is needed
                // Could alternatively use conn.getResponseMessage() or conn.getInputStream()
                conn.getResponseCode();

            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                conn.disconnect();
            }
            return null;
        }
    }
}
 try
      {
        URL url = new URL(address);
        URLConnection uc = url.openConnection();
        HttpURLConnection conn = (HttpURLConnection) uc;
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-type", "text/xml");        
        PrintWriter pw = new PrintWriter(conn.getOutputStream());
        pw.write(msg.getText());
        pw.close();
        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
        bis.close();

      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
public class RestClient {

    static Context context;
    private static int responseCode;
    private static String response;

    public static String getResponse() {
        return response;
    }

    public static void setResponse(String response) {
        RestClient.response = response;
    }

    public static int getResponseCode() {
        return responseCode;
    }

    public static void setResponseCode(int responseCode) {
        RestClient.responseCode = responseCode;
    }

    public static void Execute(String requestMethod, String jsonData, String urlMethod, Context contextTemp, HashMap<String, Object> params) {
        try {
            context = contextTemp;
            String ip = context.getResources().getString(R.string.ip);
            StringBuilder urlString = new StringBuilder(ip + urlMethod);
            if (params != null) {
                for (Map.Entry<String, Object> para : params.entrySet()) {
                    if (para.getValue() instanceof Long) {
                        urlString.append("?" + para.getKey() + "=" +(Long)para.getValue());
                    }
                    if (para.getValue() instanceof String) {
                        urlString.append("?" + para.getKey() + "=" +String.valueOf(para.getValue()));
                    }
                }
            }

            URL url = new URL(urlString.toString());

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setReadTimeout(10000 /*milliseconds*/);
            conn.setConnectTimeout(15000 /* milliseconds */);


            switch (requestMethod) {
                case "POST" : case "PUT":
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                    conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
                    conn.connect();
                    OutputStream os = new BufferedOutputStream(conn.getOutputStream());
                    os.write(jsonData.getBytes());
                    os.flush();
                    responseCode = conn.getResponseCode();
                    break;
                case "GET":
                    responseCode = conn.getResponseCode();
                    System.out.println("GET Response Code :: " + responseCode);
                    break;
                 break;

            }
            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuffer tempResponse = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    tempResponse.append(inputLine);
                }
                in.close();
                response = tempResponse.toString();
                System.out.println(response.toString());
            } else {
                System.out.println("GET request not worked");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}