2016-10-25 77 views
0

當我使用python-script將請求發送到此服務器時,我的應用程序構建了一個服務器端,但它與我的應用程序無效。[Android] -POST Json with HttpUrlConnection

服務器:

服務器包含一個數據庫。當我發送一個JSON {"name":"your_name"}時,服務器保存在數據庫中的名稱。

應用(Android):

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    buttonSend=(Button)findViewById(R.id.button_send); 


    buttonSend.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      AsyncTaskRunner postReq = new AsyncTaskRunner(); 
      postReq.execute("start"); 

     } 
    }); 
} 

private class AsyncTaskRunner extends AsyncTask<String,String,String>{ 
    @Override 
    protected String doInBackground(String... params) { 
     try { 
      String url="my url"; 
      URL object=new URL(url); 

      HttpURLConnection con = (HttpURLConnection) object.openConnection(); 
      con.setDoOutput(true); 
      con.setDoInput(true); 
      con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); 
      con.setRequestMethod("POST"); 

      JSONObject cred = new JSONObject(); 
      cred.put("name","my_name") 

      OutputStream os = con.getOutputStream(); 
      os.write(cred.toString().getBytes("UTF-8")); 
      os.close(); 


     } 
     catch (Exception e){ 
      Log.v("ErrorAPP",e.toString()); 
     } 
     return ""; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     super.onPostExecute(s); 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 

    @Override 
    protected void onProgressUpdate(String... values) { 
     super.onProgressUpdate(values); 
    } 
} 

在我運行此應用程序的手機,我嗅出數據,我看到的是,應用程序發送一個請求到服務器,但該數據包不包含JSON

+0

你必須使用傑克遜寫JSON轉換爲字符串。 OutputStream os = con.getOutputStream(); ObjectWriter writer = getMapper()。writer(); String jsonObject = writer.writeValueAsString(request); os.write(jsonObject); –

+0

檢查了這一點:http://stackoverflow.com/a/21405096/1263362 – Sayem

+0

爲什麼與傑克遜?還有,這是什麼?? – israelbenh

回答

0

我解決了它!

變化是:

OutputStream os = con.getOutputStream(); 
     os.write(cred.toString().getBytes("UTF-8")); 
     os.close(); 

到:

DataOutputStream localDataOutputStream = new DataOutputStream(con.getOutputStream()); 
      localDataOutputStream.writeBytes(cred.toString()); 
      localDataOutputStream.flush(); 
      localDataOutputStream.close();