2016-04-06 4 views
1

Мой тип клиента - андроид, а язык - Java.Отправить строку json на сервер

Этот класс подключается к серверу и получает выходной поток на подключенный сервер.

class ConnectToServer extends AsyncTask<Void, Void, Void> 
{ 

    @Override 
    protected Void doInBackground(Void... params) 
    { 
     try { 
      socket = new Socket(ip,port); 
      output = new DataOutputStream(socket.getOutputStream()); 
      Log.d(TAG, "Connected To Server!"); 

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

     return null; 
    } 
} 

class SendToServer extends AsyncTask<Void, Void, Void> 
{ 
    //Our Json object 
    JSONObject obj;// = new JSONObject(); 

    //this class is called when the login button is pressed, it sends the username and password as arguments 
    public SendToServer(String username, String password) 
    { 
     //instantiate the new object 
     obj = new JSONObject(); 

     try { 
      //create the first field Type 
      obj.put("Type", new Integer(1)); //Type is something our Server will switch against-Type 1 = login request 
      obj.put("username", username); //our server will get username 
      obj.put("password",password); //our server will get password 
     } catch (JSONException e) { 
      e.printStackTrace();  //if we get problems let the developer know 
     } 
    } 
    @Override 
    protected Void doInBackground(Void... params) 
    { 
     String jsonText = obj.toString();      //convert our json object into a string 
     byte[] b =jsonText.getBytes(Charset.forName("UTF-8")); //convert our json object into a byte array 
     try { 
      output.writeInt(b.length); // write length of the message 
      output.write(b);   // write the message 
      output.flush();   //flush - empties the pipe 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 
} 

}

Цель этого кода послать серверу учетные данные пользователей.

В C# Сервер

private void serverClient() 
    { 
     while(true) 
     { 
      int len = ns.ReadByte(); //read how much data 

      if (len == 0) //if this == 0 this means client has quit the program 
       break;  //break out of loop and remove client from array list 

      if (len > 0) //we have a message 
      { 
       //read mess 
       byte[] message = new byte[len];   //create byte array 
       ns.Read(message, 0, message.Length); //read into the message byte array 
       string text = Encoding.ASCII.GetString(message, 0, len); 
       string text1 = Encoding.UTF8.GetString(message, 0, len); //build string from byte array up to how much data we got. 

       Console.WriteLine(text1); 
      } 
     } 

     removeClients(); 

    } 

Так Android клиент будет отправлять учетные данные, но при вызове SendToServer класса, клиент отключается от сервера.

Как я могу отправить строку Json на свой сервер C#, чтобы затем прочитать строку и сериализовать ее в объект в зависимости от полей.

+1

Ваш код java, насколько я могу судить, записывает только объект json - не имеет ничего общего с сетью. – Rob

+1

@Rob Я добавил код, который показывает, что клиент подключается к серверу и получает выходной поток. Затем в классе «SendToServer» используется метод «write» для потока вывода. – Moynul

ответ

1
private void updateDataToServer() { 

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("name", name)); 
    nameValuePairs.add(new BasicNameValuePair("score", score)); 

    try { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(url_update); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 
     Log.e("pass 1", "connection success "); 
    } catch (Exception e) { 
     Log.e("Fail 1", e.toString()); 
     Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     result = sb.toString(); 
     Log.e("pass 2", "connection success "); 
    } catch (Exception e) { 
     Log.e("Fail 2", e.toString()); 
    } 

    try { 
     JSONObject json_data = new JSONObject(result); 
     code = (json_data.getInt("code")); 

     if (code == 1) { 
      /* 
      * Toast.makeText(getBaseContext(), "Update Successfully", 
      * Toast.LENGTH_SHORT).show(); 
      */ 
     } else { 
      Toast.makeText(getBaseContext(), "Sorry, Try Again", Toast.LENGTH_LONG).show(); 
     } 
    } catch (Exception e) { 
     Log.e("Fail 3", e.toString()); 
    } 

} 

class PostDataToServer extends AsyncTask<String, String, String> { 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     /* 
     * pDialog = new ProgressDialog(MainActivity.this); 
     * pDialog.setMessage("Please wait..."); pDialog.show(); 
     */ 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(url_create_product); 

     try { 
      name = edt_name.getText().toString(); 
      score = edt_score.getText().toString(); 
      quocgia = edt_quocgia.getText().toString(); 
      // Add your data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("name", name)); 
      nameValuePairs.add(new BasicNameValuePair("score", score)); 
      nameValuePairs.add(new BasicNameValuePair("quocgia", quocgia)); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      // Execute HTTP Post Request 
      HttpResponse response = httpclient.execute(httppost); 

     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     /* 
     * if (pDialog.isShowing()) { pDialog.dismiss(); 
     * Toast.makeText(getApplication(), "Complete", 
     * Toast.LENGTH_LONG).show(); } 
     */ 
    } 
} 

Надеется, что это помогает вам

+0

Здравствуйте, я смотрел HTTP-запросы, сообщения и получал. Но мой идеальный план - использовать Sockets. Я не хочу использовать веб-сервер. Я хочу, чтобы мой клиент подключился к серверу. – Moynul

+0

http://www.jayrambhia.com/blog/android-wireless-connection-2/ Вы можете это увидеть! –

+0

http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html –

0

Вы читаете строки, но вы не писать строки. Добавьте терминатор линии в отправляемое сообщение или используйте функцию println() вместо write().