2016-05-25 13 views
0

おはよう、アンドロイドはhttp投稿リクエストを送信します - 正しい方法

私はアンドロイドでHTTP POSTリクエストを作成するためのチュートリアルを見つけました。 このコードはうまく動作しますが、このコードがこれを行う最善の方法であるかどうか、あるいはアイデアがあれば、どのように最適化できるかを知りたいと思います。

private class PostClass extends AsyncTask<String, String, String> { 

     Context context; 

     public PostClass(Context c){ 
      this.context = c; 
     } 


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

       URL url = new URL("xxxx"); 

       HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
       String urlParameters = "xxx"; 

       connection.setRequestMethod("POST"); 
       connection.setDoOutput(true); 
       DataOutputStream dStream = new DataOutputStream(connection.getOutputStream()); 
       dStream.writeBytes(urlParameters); 
       dStream.flush(); 
       dStream.close(); 


       BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
       final String response = br.readLine(); 
       br.close(); 

       return response; 


      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      return null; 
     } 




     protected void onPostExecute(String result){ 
      Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show(); 
     } 

    } 
+1

RESTリクエストにVolleyライブラリを使用することをお勧めします。 AsyncTaskの方が簡単です。 – Tomislav

+0

はいいいですね。 [Docs says](https://developer.android.com/reference/java/net/HttpURLConnection.html) –

+0

ライブラリを使用していない限り、Googleのデベロッパーガイドには正しい、標準的な方法があります。 –

答えて

1

同期の頻度に基づいて、あなたはVolleyを使用することができます。また、POSTリクエストでの複数のパラメータをに送信する必要がある場合は、次のコードを使用することもできます。ここで

HttpClient httpclient = new DefaultHttpClient(); 
     String responseStr=""; 
     String URL=Constants.API_URL;#URL where request needs to be sent 
     HttpPost httppost = new HttpPost(URL); 

     try { 
      // Add your data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
      nameValuePairs.add(new BasicNameValuePair("id", pick_up_id)); 
      nameValuePairs.add(new BasicNameValuePair("driver_photo", strPhoto));#image in form of Base64 String which you need to send 

      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

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

      int responseCode = response.getStatusLine().getStatusCode(); 
      switch(responseCode) { 
      case 200: 
       HttpEntity entity = response.getEntity(); 
       if(entity != null) { 
        String responseBody = EntityUtils.toString(entity); 
        responseStr=responseBody; 
       } 
       break; 
      } 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
     } 
     System.out.println("this is response "+responseStr); 
+0

HTTPClientはAPI 23で廃止予定です。依存関係を追加する必要があります。 –

0

は、このポスト要求は、このcompile 'com.mcxiaoke.volley:library:1.0.19'ボレーのバージョンを使用しているVolly library

 void MakePostRequest() { 
      StringRequest postRequest = new StringRequest(Request.Method.POST, EndPoints.BASE_URL_ADS, 
        new Response.Listener<String>() { 
         @Override 
         public void onResponse(String response) { 
          try { 
           JSONObject jsonResponse = new JSONObject(response); 
           value1= jsonResponse.getString("Your ID1"); 
           value2= jsonResponse.getString("Your ID2"); 

          } catch (JSONException e) { 
           e.printStackTrace(); 
           banner_id = null; 
           full_id = null; 
          } 
         } 
        }, 
        new Response.ErrorListener() { 
         @Override 
         public void onErrorResponse(VolleyError error) { 
          error.printStackTrace(); 
          value1= null; 
          value2= null; 
         } 
        } 
      ) { 
      // here is params will add to your url using post method 
       @Override 
       protected Map<String, String> getParams() { 
        Map<String, String> params = new HashMap<>(); 
        params.put("app", getString(R.string.app_name)); 
        //params.put("2ndParamName","valueoF2ndParam"); 
        return params; 
       } 
      }; 
      Volley.newRequestQueue(this).add(postRequest); 
     } 

使用例のHttp POSTリクエストです。

パラメータとしてアプリ名を追加するだけです。さらにパラメータを追加できます。

0

はい正しいです。私はこのような要求を処理するために、ボンネットの下にこれに似ている、ライブラリを作った:https://github.com/gjudkins/GjuddyRequest

はあなたに依存関係を追加build.gradle:

repositories { 
    maven { 
    url 'https://dl.bintray.com/gjudkins/maven' 
    } 
} 

dependencies { 
    compile 'com.gjuddy:easyhttprequest:0.1.17' 
} 

その要求を作ることは、このようになります:

// define headers 
ContentValues headers = new ContentValues(); 
bodyParams.put("FirstHeader","header-value"); 
bodyParams.put("AnotherHeader","add as many as you want"); 

// define parameters 
ContentValues bodyParams = new ContentValues(); 
bodyParams.put("name","the_name"); 
bodyParams.put("another_param","add as many as you want"); 

// define how GjuddyRequest will format the body/parameters of the request 
// !! The appropriate headers for the ContentType defined here are AUTOMATICALLY added to the request !! 
GjuddyRequest.ContentType bodyFormat = GjuddyRequest.ContentType.x_www_url_form_urlencoded; 

// make the POST request 
GjuddyRequest.getInstance().makePostAsync("https://your.api.url", bodyParams, bodyFormat, headers, new GjuddyRequest.HttpRequestCallback() { 
    @Override 
    public void requestComplete(GjuddyResponse response) { 
     // check for errors 
     if (response.getErrors() == null) { 
      // the GjuddyResponse object can automatically retrieve the response 
      // as a String, JSONObject, or JSONArray 
      JSONObject jsonResponse = response.toJSONObject(); 
      Log.e("GJUDDY", response.toString()); 
     } else { 
      Log.e("GJUDDY", response.getErrorString()); 
     } 
    } 
}); 

リンクのGitHubのreadmeは、使い方が詳しく分かりますが、かなり簡単です。

+0

OkHttpができることのように見えるので、学習体験としてこれを作ったと思いますか? –

+0

@ cricket_007、基本的にはyesです。私は、httpリクエスト用のライブラリを使用したことがなく、HttpUrlConnection用の独自のラッパーを作成し続けました。私は結局(ちょうど最近)、それを図書館にすることにしました。 – gjudkins

関連する問題