将json对象发送到服务器

时间:2017-08-24 14:28:32

标签: android json

我正在尝试将一个简单的json对象发送到服务器。我可以使用postman将json对象发送到服务器而没有任何问题。我正在使用Tom Alabaster从以下链接获得正确答案的代码: How To Send json Object to the server from my android app

但是在以下行中找到File not found错误(给出我的服务器名称): DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());

服务器通过邮递员工作没有任何问题。我想更深入地分析这个问题。我如何捕获任何有用的错误代码?

Error code:
08-24 18:21:21.193 17299-20507/com.tulga.nar.mytracker I/System.out: 
(HTTPLog)-Static: isSBSettingEnabled false
08-24 18:21:21.623 17299-20507/com.tulga.nar.mytracker W/System.err: 
java.io.FileNotFoundException: https://myserver....../mydatabase
08-24 18:21:21.623 17299-20507/com.tulga.nar.mytracker W/System.err:   
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConn
ectionImpl.java:242)
08-24 18:21:21.623 17299-20507/com.tulga.nar.mytracker W/System.err:   at 

com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210) 08-24 18:21:21.623 17299-20507 / com.tulga.nar.mytracker W / System.err:at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25) 08-24 18:21:21.623 17299-20507 / com.tulga.nar.mytracker W / System.err:at com.tulga.nar.mytracker.MainActivity $ SendDeviceDetails.doInBackground(MainActivity.java:58) 08-24 18:21:21.623 17299-20507 / com.tulga.nar.mytracker W / System.err:at com.tulga.nar.mytracker.MainActivity $ SendDeviceDetails.doInBackground(MainActivity.java:33) 08-24 18:21:21.623 17299-20507 / com.tulga.nar.mytracker W / System.err:在android.os.AsyncTask $ 2.call(AsyncTask.java:295) 08-24 18:21:21.623 17299-20507 / com.tulga.nar.mytracker W / System.err:at java.util.concurrent.FutureTask.run(FutureTask.java:237) 08-24 18:21:21.623 17299-20507 / com.tulga.nar.mytracker W / System.err:at android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:234) 08-24 18:21:21.623 17299-20507 / com.tulga.nar.mytracker W / System.err:at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 08-24 18:21:21.623 17299-20507 / com.tulga.nar.mytracker W / System.err:at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:588) 08-24 18:21:21.623 17299-20507 / com.tulga.nar.mytracker W / System.err:at java.lang.Thread.run(Thread.java:818) 08-24 18:21:51.523 17299-17299 / com.tulga.nar.mytracker V / ActivityThread:updateVisibility:ActivityRecord {3cf0352 token=android.os.BinderProxy@24d32cf {com.tulga.nar.mytracker / com.tulga。 nar.mytracker.MainActivity}} show:true

3 个答案:

答案 0 :(得分:0)

尝试像以前一样使用HTTPUrlConnection,但也像这样设置请求属性(如果你还没有):

将url定义为服务器的url url。

JSONObject params = new JSONObject();
    try {
        params.put("some_key_1", value_1);
        params.put("some_key_2", value_2);
    } catch (JSONException | NumberFormatException exception) {
        exception.printStackTrace();
    }

HttpURLConnection connection = (HttpURLConnection) url.getUrl().openConnection();   


        connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            osw = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            // Send request.
            osw.write(params.toString());
            osw.flush();
            osw.close();

答案 1 :(得分:0)

登录示例。这里我们发布登录用户名和密码

        String lname = "";
    try {
        url = new URL(SNFServerURL+SNFAuthResource);
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url.toString());
        post.setHeader("Content-type", "application/json");
        post.setHeader("Accept", "application/json");
        JSONObject object = new JSONObject();
        String message;

        object.put("password", Flags.password);
        object.put("username", Flags.username);
        message = object.toString();
        post.setEntity(new StringEntity(message, "UTF8"));
        HttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (200 == statusCode) {
            String json = EntityUtils.toString(response.getEntity());
            JSONObject result = new JSONObject(json);
            token = result.getString("token");
            TokenActivity.fname = result.getString("firstName");
            TokenActivity.lname = result.getString("lastName");


        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

答案 2 :(得分:-1)

Button submitButton = (Button) findViewById(R.id.submit_button);

submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
    JSONObject postData = new JSONObject();
    try {
        postData.put("name", name.getText().toString());
        postData.put("address", address.getText().toString());
        postData.put("manufacturer", manufacturer.getText().toString());
        postData.put("location", location.getText().toString());
        postData.put("type", type.getText().toString());
        postData.put("deviceID", deviceID.getText().toString());

        new SendDeviceDetails.execute("http://52.88.194.67:8080/IOTProjectServer/registerDevice", postData.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
});
private class SendDeviceDetails extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {

    String data = "";

    HttpURLConnection httpURLConnection = null;
    try {

        httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
        httpURLConnection.setRequestMethod("POST");

        httpURLConnection.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
        wr.writeBytes("PostData=" + params[1]);
        wr.flush();
        wr.close();

        InputStream in = httpURLConnection.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(in);

        int inputStreamData = inputStreamReader.read();
        while (inputStreamData != -1) {
            char current = (char) inputStreamData;
            inputStreamData = inputStreamReader.read();
            data += current;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    }

    return data;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    Log.e("TAG", result); // this is expecting a response code to be sent from your server upon receiving the POST data
}

}