2016-02-02 13 views
0

我有一臺服務器使用mongodb,mongoose和node.js. 我已經實現了一些GET和POST方法。Android HttpURLConnection發送數據的請求不工作,但JavaScript XMLHttpRequest確實

裏面一個HTML網站,我可以一個XMLHttpRequest內張貼數據到服務器裏面的javascript如下:

function postPlantType(base64){ 
    var httpPost = new XMLHttpRequest(), 
     path = "http://...",    // real URL taken out here 
     header = ('Content-Type','application/json'), 
     data = JSON.stringify({image:base64}); 
    httpPost.onreadystatechange = function(err) { 
     if (httpPost.readyState == 4 && httpPost.status == 201){ 
      console.log(httpPost.responseText); 
     } else { 
      console.log(err); 
     } 
    }; 

    path = "http://..."     // real URL taken out here 
    httpPost.open("POST", path, true); 
    httpPost.send(data); 
} 

能正常工作。現在我想創建一個Android應用程序,利用這樣的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; charset=UTF-8"); 

      String json = "{\"image\":\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYE...\"}"; 

      Log.d("json", json.toString()); 

      conn.setRequestProperty("Content-length", json.getBytes().length + ""); 
      conn.setDoInput(true); 
      conn.setUseCaches(false); 
      conn.setAllowUserInteraction(false); 

      OutputStream os = conn.getOutputStream(); 
      os.write(json.getBytes("UTF-8")); 
      os.close(); 

      // Starts the query 
      conn.connect(); 
      response = conn.getResponseCode(); 
      if (response >= 200 && response <=399){ 
       is = conn.getInputStream(); 
      } else { 
       is = conn.getErrorStream(); 
      } 

      // Convert the InputStream into a string 
      String contentAsString = readIt(is, 200); 
      responseString = contentAsString; 
      conn.disconnect(); 
     } catch (Exception e) { 
      responseString = "error occured: "+e; 


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

    protected void onPostExecute(String result){ 

     // TODO: nothing(?) 
     // give user feedback(?) 
    } 

} 

注意:如果我將json字符串更改爲無效的json內容,例如刪除最後一個「}」,服務器的響應是

400 "code":"InvalidContent","message":"Invalid JSON: Unexpected end of input" 

所以我承擔全部JSON字符串必須是正確的,如果它的不變。

我硬編碼的base64encoded圖像字符串在這裏,而不是編碼一個真實的圖像,因爲測試問題。您可以在jsfiddle處看到圖像。 如果我看到它正確,它完全相同的請求,從我的JavaScript完成,但我得到500內部服務器錯誤。 然而,爲了獲得更多的信息,這裏是服務器的功能,即稱爲該請求URL:

function postNewPlantType(req, res, next){ 
    var json = JSON.parse(req.body); 
    newPlantTypeData = { 
     image:json.image 
    }; 

    var imageBuffer = decodeBase64Image(json.image); 

    newPlantType = new Planttype(newPlantTypeData); 

    newPlantType.save(function(err){ 
     if (err) return next(new restify.InvalidArgumentError(JSON.stringify(err.errors))); 
     var fileName = cfg.imageFolder + "" + newPlantType._id + '.jpeg'; 
     fs.writeFile(fileName, imageBuffer.data, function(error){ 
      if (error) log.debug(error); 
      log.debug("PlantType-ImageFile successfully created on server."); 
     }); 
     res.send(201, newPlantType); 
     log.debug("PlantType successfully saved in database."); 
    }); 
} 

我想知道的是,JavaScript的請求工作,但Android的請求不。所以我認爲我的android代碼中必須有一個錯誤。你能幫我解釋一下,錯誤是什麼,我必須改變什麼?

回答

0

經過大量的調查,我終於通過改變線路

conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); 

conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); 

得到了201響應的天那麼..我發送一個編碼的JSON而不是一個JSON本身...

0

你可能需要妥爲編碼:

conn.connect(); 
DataOutputStream printout = new DataOutputStream(conn.getOutputStream()); 
printout.write(URLEncoder.encode(json.toString(),"UTF-8")); 
printout.flush(); 
printout.close(); 
response = conn.getResponseCode(); 
... 
+0

不,已經做到了。沒有不同 – MojioMS

相關問題