从Android发送任何HTTP POST到我的服务器导致FileNotFoundException

时间:2016-02-01 14:23:52

标签: android http-post httpurlconnection

我有一台使用mongodb,mongoose和node.js运行的服务器。所有服务器方法(GET和POST)都在我的HTML javascripts上进行测试,并且它们按预期工作。 我想在我的Android应用程序中使用这些方法。问题: 虽然GET方法按预期响应,但所有POST请求都会导致Java.io.FileNotFoundException。 我一直在寻找尝试过几个没有成功的想法。 以下是我的应用程序中一个HTTP POST请求的代码:

    private class PostNewPlantTask extends AsyncTask<String, Integer, String> {
    String responseString = "";
    int response;
    InputStream is = null;

    protected String doInBackground(String... urls){
        DataOutputStream wr=null;
        try {
            URL url = new URL(urls[0]);  // urls[0] is the url of the http request "http://www..."
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Content-Type", "application/json");

            // encode base64 from image
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] b = baos.toByteArray();
            encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);

            // Create JSONObject:
            JSONObject jsonParam = new JSONObject();
            //jsonParam.put("loc", "["+plant_location[0]+","+plant_location[1]+"]");
            jsonParam.put("image", encodedString);
            //Log.d("POSTING PLANT JSON", jsonParam.toString());
            //Log.d("Plant loc",jsonParam.get("loc").toString());

            //wr = new DataOutputStream(conn.getOutputStream());
            //wr.writeBytes(jsonParam.toString());

            //wr.flush();
            //wr.close();


            // Starts the query
            conn.connect();
            response = conn.getResponseCode();
            Log.d("HTTP POST", "#1");

            is = conn.getInputStream();
            Log.d("HTTP POST", "#2");

            // Convert the InputStream into a string
            String contentAsString = readIt(is, 1000);
            Log.d("HTTP POST","#3");
            responseString = contentAsString;
        } catch (Exception e) {
            responseString = "error occured: "+e;
            // Test: write string into textfile

        } finally {
            if (is != null){
                try { is.close();} catch (Exception e) {Log.d("HTTP GET planttypes","Exception occured at closing InputStream: "+e);}
            }
        }
        Log.d("HTTP POST plants", "The response is: " + response + responseString);



        return responseString;
    }

我添加了那些Log.d来缩小FileNotFoundException发生的位置。这里的日志:

02-01 15:16:50.088 27382-28809/com.example.openplantmap D/HTTP POST: #1
02-01 15:16:50.096 27382-28809/com.example.openplantmap D/HTTP POST plants: The response is: 500error occured: java.io.FileNotFoundException: https://www......

因此错误FileNotFoundException发生在

is = conn.getInputStream();

你知道我的问题是什么吗?我需要改变什么才能让它发挥作用?

我称之为帖子的部分:

// Submit Button:
    Button btn_submit = (Button) findViewById(R.id.btn_submitPlant);
    btn_submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            new PostNewPlantTask().execute("https://www...."); // I prefer not to show the actual url here

            Log.d("SUBMIT PRESSED.","SUBMIT PRESSED");
            // TODO: GIVE FEEDBACK TO THE USER
        }
    });

1 个答案:

答案 0 :(得分:0)

修改

而不是wr.writeBytes(jsonParam.toString());

尝试wr.write(URLEncoder.encode(jsonParam.toString(),"UTF-8"));

并取消注释所有写入流的行。

<强>原始

  

回复是:500

连接的响应是错误500,或Internal Server Error。也许你的服务器端脚本有问题,而不是你的android代码。我会从那个角度进行调试。

您可以使用getResponseCode()方法确定是否出现问题,如果出现问题,且错误代码为400或更高,则响应将包含一个正文,您可以使用{{1}访问该正文}