将变量发送到REST API以保存在服务器上

时间:2018-01-16 14:38:12

标签: android rest post httprequest put

我现在正在努力解决这个问题一段时间以来,我真的很失落。

我已经在netbeans中编写了一个REST服务,我已经通过了Json数据并测试它是否可以使用Postman工作,并且它已成功保存到数据库中。

现在,我希望将移动应用程序中的变量发送到该REST api,以便将它们保存到数据库中。

我已经看过很多关于此问题的答案,但是没有一个能完全解释我如何做到这一点。理想情况下,我试图将我的移动应用程序中的数据发布或PUT到我的数据库中。

这是我到目前为止所尝试的内容:

 submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            details = editTextDetails.getText().toString();
            getCurrentDateandTime();

            String url = "http://localhost:8080/engAppApi/webservices/engineerTable/";

            HttpClient client = new DefaultHttpClient();

            HttpPost request = new HttpPost(url);

            JSONObject params = new JSONObject();

            try {
                params.put("machinetype", machineType);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            try {
                params.put("workordernumber", workOrderNumber);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("employeename", employee);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("activity", activity);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("durationhours", durationHours);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("durationmins", durationMins);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("downtimehours", downTimeHours);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("downtimemins", downTimeMins);
            } catch (JSONException e) {
                e.printStackTrace();
            }


            try {
                params.put("details", details);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                params.put("currentdateandtime", currentDateandTime);
            } catch (JSONException e) {
                e.printStackTrace();
            }


            StringEntity jsonEntity = null;
            try {
                jsonEntity = new StringEntity(params.toString());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            request = new HttpPost(url);

            request.addHeader("Content-Type", "application/json");


            request.setEntity(jsonEntity);

            try {
                HttpResponse response = client.execute(request);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    });
}

有人可以指出我正确的方向吗

提前致谢!

2 个答案:

答案 0 :(得分:1)

只需使用改造2连接服务器即可。 请参阅此link

答案 1 :(得分:0)

你对如何进行职位申请有一个想法,但你有几个问题。第一个也是更重要的问题是,如果要从服务器检索信息,则必须将代码放在异步任务中。您无法在UI线程中执行此操作。所以,我将与你分享一个实现你需要的所有逻辑的类,你只需要使用它。首先你需要使用gson,看看如何在这里使用它

https://github.com/google/gson

代码就在这里。它有两种方法,一种用于GET,另一种用于POST。

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrador on 4/27/2017.
 */

public class JsonReaderFromUrl {

    public static final int SUCCESS = 0;
    public static final int FAILED = 1;
    public static final int PROGRESS = 2;


    public interface OnJesonInterface{
        void OnJsonReceive(int status, JSONObject jsonObject, int key);
    }

    public JsonReaderFromUrl() {
    }

    public void getJsonFromUrlPost(final String url, final OnJesonInterface onJesonInterface, final String body, final int key){
        new AsyncTask<Void, String, String>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                onJesonInterface.OnJsonReceive(PROGRESS,null,0);
            }

            @Override
            protected String doInBackground(Void... params) {
                if(android.os.Debug.isDebuggerConnected())
                    android.os.Debug.waitForDebugger();
                try {
                    URL urlJson = new URL(url);
                    HttpURLConnection connection  = (HttpURLConnection) urlJson.openConnection();
                    connection.setDoInput(true);
                    connection.setRequestProperty("Content-Type","application/json");
                    connection.setRequestMethod("POST");
                    OutputStream outputStream = connection.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                    writer.write(body);
                    writer.flush();
                    writer.close();
                    outputStream.close();
                    connection.connect();
                    StringBuilder stringBuilder = new StringBuilder();
                    int httpStatus = connection.getResponseCode();
                    if (httpStatus == HttpURLConnection.HTTP_CREATED){
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(connection.getInputStream(),"utf-8")
                        );
                        String line = "";
                        while ((line = br.readLine()) != null){
                            stringBuilder.append(line + "\n");
                        }
                        br.close();
                        return stringBuilder.toString();
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s != null){
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        onJesonInterface.OnJsonReceive(SUCCESS,jsonObject,key);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                else {
                    onJesonInterface.OnJsonReceive(FAILED,null,0);
                }
            }
        }.execute();
    }

    public void getJsonFromUrl(final String url, final OnJesonInterface onJesonInterface){
        AsyncTask<Void,String,String> asyncTask = new AsyncTask<Void, String, String>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                onJesonInterface.OnJsonReceive(PROGRESS,null,0);
            }

            @Override
            protected String doInBackground(Void... params) {
                try {
                    URL urlJson = new URL(url);
                    HttpURLConnection connection = (HttpURLConnection) urlJson.openConnection();
                    connection.connect();

                    InputStream stream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
                    StringBuffer stringBuffer = new StringBuffer();
                    String line = "";
                    while ((line = reader.readLine()) != null){
                        stringBuffer.append(line + "\n");
                        Log.d("RESPONDE JSON: ",">" + line);
                    }
                    return stringBuffer.toString();



                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s != null){
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        onJesonInterface.OnJsonReceive(SUCCESS,jsonObject,0);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                else {
                    onJesonInterface.OnJsonReceive(FAILED,null,0);
                }
            }
        }.execute();
    }
}

在您需要的地方导入此类并使用它PD:键值是一个int,可用于检索与每个请求相对应的响应,以防您在此类中使用大量请求。