Matt02's Note

仕事関係。Android、Unity、cocos2d-xに関してのメモを書いていきます。

AndroidでのPostとGet(送信)

動くかわからないのであしからず…

 

■Get送信 

public String httpGet(HttpParams httpParams, HttpClient httpClient, String url) {

       HttpResponse httpResponse = null;

       String result = "";

       HttpGet httpGet = new HttpGet(url);

       httpGet.setParams(httpParams);

       try {

           httpResponse = httpClient.execute(httpGet);

           int status = httpResponse .getStatusLine().getStatusCode();

           if (status >= 400) {

               Log.i("Failure = "+status );

           } else {

               Log.i("Success! = "+status );

               InputStream content = httpResponse .getEntity().getContent();

               BufferedReader reader = new BufferedReader(

                       new InputStreamReader(content));

               try {

                   StringBuilder buf = new StringBuilder();

                   String line;

                   while ( (line = reader.readLine() ) != null) {

                       buf.append(line);

                   }

                   result = buf.toString();

               } finally {

                   content.close();

                   reader.close();

               }

           }

       } catch (ClientProtocolException e) {

           e.printStackTrace();

       } catch (IOException e) {

           e.printStackTrace();

       }

       return result;

   }

 

 

■Post送信

public String httpPost(HttpParams httpParams, DefaultHttpClient httpClient, String url) {

        HttpResponse httpResponse = null;

        String result = "";

        HttpPost httpPost = new HttpPost(url);

        httpPost.setParams(httpParams);

        try {

            httpResponse = httpClient.execute(httpPost);

            int status = httpResponse .getStatusLine().getStatusCode();

            if (status >= 400) {

                Log.i("","Failure = "+status );

           } else {

               Log.i("Success! = "+status );

                InputStream content = httpResponse .getEntity().getContent();

                BufferedReader reader = new BufferedReader(

                        new InputStreamReader(content));

                try {

                    StringBuilder buf = new StringBuilder();

                    String line;

                    while ( (line = reader.readLine() ) != null) {

                        buf.append(line);

                    }

                    result = buf.toString();

                } finally {

                    content.close();

                    reader.close();

                }

            }

        } catch (ClientProtocolException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        return result;

    }