2015-10-27 43 views
0

我需要發送一個字符串到我的Web服務,我對如何使用HttpURLConnection發送字符串有疑問。如何發送字符串使用HttpURLConnection android

觀測數據:在字符串「結果」我有這樣的:

{"sex":"Famale","nome":"Larissa Aparecida Nogueira","convenios":[{"convenio":2,"tipo":"Principal","number":"44551-1456-6678-3344"}],"user":"lari.ap","email":"[email protected]","cell":"(19)98167-5569"} 

下面是我的代碼:

public UsuerService(Context context, String result) { 
     this.progressDialog = new ProgressDialog(context); 
     this.context = context; 
     this.result = result; 
    } 

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

     String responseString = ""; 
     try { 
      URL url = new URL(Constants.USUARIO + "/createUsuario"); 
      HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
      httpURLConnection.setRequestMethod("POST"); 


      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); 
      String inputLine; 
      StringBuilder response = new StringBuilder(); 

      while ((inputLine = bufferedReader.readLine()) != null) { 
      response.append(inputLine); 
      } 

      result = response.toString(); 
      bufferedReader.close(); 
      } catch (Exception e) { 
      Log.d("InputStream", e.getMessage()); 
     } 

     return null; 
    } 

我有一個拿起我的數據,並將其解析到JSONObject的一類。 我需要了解如何使用HttpURLConnection發送我的object.toString()Web服務。

以下是代碼:

public String parserUsuarioJson(){ 

    JSONObject object = new JSONObject(); 

    try { 
     object.put(Constants.KEY_NAME, mUsuario.getNome()); 
     object.put(Constants.KEY_EMAIL, mUsuario.getEmail()); 
     object.put(Constants.KEY_USER, mUsuario.getUser()); 
     object.put(Constants.KEY_PASS, mUsuario.getSenha()); 
     object.put(Constants.KEY_SEX, mUsuario.getSexo()); 
     object.put(Constants.KEY_CELLPHONE, mUsuario.getCelular()); 

     JSONArray array = new JSONArray(); 

     for(int i = 0; i < mUsuario.getUsuarioConvenios().size() ; i++){ 
      JSONObject convenio = new JSONObject(); 

      convenio.put(Constants.KEY_CONVENIO, mUsuario.getUsuarioConvenios().get(i).getConvenio().getId()); 
      convenio.put(Constants.KEY_NUMBER, mUsuario.getUsuarioConvenios().get(i).getNumero()); 
      convenio.put(Constants.KEY_TYPE, mUsuario.getUsuarioConvenios().get(i).getTipo()); 

      array.put(convenio); 
     } 
     object.put(Constants.KEY_CONVENIOS, array); 
    } catch (JSONException e) { 
     Log.e("Register", e.getMessage()); 
    } 

    return object.toString(); 

} 

預先感謝。 :)

+0

在android中對所有NetworkCalls使用volley。它的Google圖書館非常易於使用。 http://developer.android.com/training/volley/index.html – Arshad

+1

你應該將這些信息假名,因爲你剛在網上發佈了一些女人的手機號碼! – evandentremont

回答

0

使用NameValuePairList發送數據。

嘗試這樣的事情......

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(Constants.USUARIO + "/createUsuario"); 

try { 
     // Add your key-value pair here 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
     nameValuePairs.add(new BasicNameValuePair("sex", "female")); 
     nameValuePairs.add(new BasicNameValuePair("nome", "Larissa Aparecida Nogueira")); 
     // set all other key-value pairs 

     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     HttpResponse response = httpclient.execute(httppost); 

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

對於使用HTTP POST通過網絡發送JSON對象。

通過JSON字符串這裏

StringEntity se = new StringEntity(object.toString()); 
httpost.setEntity(se); 
httpost.setHeader("Accept", "application/json"); 
httpost.setHeader("Content-type", "application/json"); 
HttpResponse response = httpclient.execute(httpost); 

不要忘了捕獲異常。使用HttpURLConnection的...

try { 
    //constants 
    URL url = new URL(Constants.USUARIO + "/createUsuario"); 
    String yourJsonString = object.toString(); 

    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
    conn.setRequestMethod("POST"); 
    conn.setDoInput(true); 
    conn.setDoOutput(true); 
    conn.setFixedLengthStreamingMode(yourJsonString.getBytes().length); 

    conn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); 
    conn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); 

    conn.connect(); 

    OutputStream os = new BufferedOutputStream(conn.getOutputStream()); 
    os.write(yourJsonString.getBytes()); 

    os.flush(); 

    is = conn.getInputStream(); 
} finally { 
    //clean up 
    os.close(); 
    is.close(); 
    conn.disconnect(); 
} 
+0

你好Ritesh。感謝您的回覆,但我有一個類將數據解析爲Json對象。我更新了這個課程的問題。我需要了解如何使用httpurlconnection爲我的Web服務發送object.toString()。謝謝 –

+0

好的,我已經更新了我的答案。看一看。 – Ritesh

+0

HttpClient或HttpURLConnection?我無法找到HttpClient –

0

隨着我越來越

發送JSON對象,你想一個String發送到web服務。我在這裏給你一個示例代碼,我將一些字符串值發送到一個web服務。它的工作代碼`

private class BackgroundOperation extends AsyncTask<String, Void, String> { 

     @Override 
     protected String doInBackground(String... params) 
      //Your network connection code should be here . 
      String response = postCall("Put your WebService url here"); 
      return response ; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      //Print your response here . 
      Log.d("Post Response",result); 

     } 

     @Override 
     protected void onPreExecute() {} 

     @Override 
     protected void onProgressUpdate(Void... values) {} 
    } 

     public static String postCall(String uri) { 
     String result =""; 
     try { 
      //Connect 
      HttpURLConnection urlConnection = (HttpURLConnection) ((new URL(uri).openConnection())); 
      urlConnection.setDoOutput(true); 
      urlConnection.setRequestProperty("Content-Type", "application/json"); 
      urlConnection.setRequestProperty("Accept", "application/json"); 
      urlConnection.setRequestMethod("POST"); 
      urlConnection.connect(); 
      //Write 
      OutputStream outputStream = urlConnection.getOutputStream(); 
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); 
//Call parserUsuarioJson() inside write(),Make sure it is returning proper json string . 
      writer.write(parserUsuarioJson()); 
      writer.close(); 
      outputStream.close(); 

      //Read 
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8")); 
      String line = null; 
      StringBuilder sb = new StringBuilder(); 
      while ((line = bufferedReader.readLine()) != null) { 
       sb.append(line); 
      } 
      bufferedReader.close(); 
      result = sb.toString(); 
     } catch (UnsupportedEncodingException e){ 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return result; 
    } 

現在,您可以從使用以下代碼的活動的onCreate()函數調用以上。

new BackgroundOperation().execute(""); 

注意:不要忘記提及下面權限在您的manifest.xml

<uses-permission android:name="android.permission.INTERNET" /> 

注意:確保

1。 parserUsuarioJson()返回正確的json字符串。

2。你的web服務正在運行。

+0

Hello Android Dev。感謝您的回覆,但我有一個類將數據解析爲Json對象。我更新了這個課程的問題。 –

+1

我需要了解如何發送object.toString();爲我的web服務使用httpURLConnection。謝謝:) –

+0

我編輯了答案,以滿足您的要求。如果你的parserUsuario()返回正確的json並且你的web服務正在工作,它肯定會工作。 –

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

     URL url = new URL(Constants.USUARIO + "/createUsuario"); 
     HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
     httpURLConnection.setRequestMethod("POST"); 
     httpURLConnection.setDoInput(true); 
     httpURLConnection.setDoOutput(true); 
     httpURLConnection.setFixedLengthStreamingMode(result.getBytes().length); 

     httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); 
     httpURLConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest"); 

     httpURLConnection.connect(); 

     OutputStream os = new BufferedOutputStream(httpURLConnection.getOutputStream()); 
     os.write(result.getBytes()); 
     os.flush(); 

     os = httpURLConnection.getOutputStream(); 

     os.close(); 
     httpURLConnection.disconnect(); 

    } catch (Exception e) { 
     Log.d("InputStream", e.getMessage()); 
    } 
+0

什麼是「結果」?它已被使用兩次 –

相關問題