2016-04-10 13 views
0

を使用してアンドロイドのデータを転記することはできません、私が実行しようとしていますが、私はFatalErrorExceptionを取得していますが、私は、ブラウザには、以下のWebサービス

http://localhost:8082/WebServices/Rest/courseService/LoginInfo/a:a 

にURLを使用してWebサービスのコードを実行しようとすると、それは完璧に動作し、完璧与えコードsnipetsですその結果、私は、コードの下に使用してアンドロイドと同じことを行うことはできません

私は

public class ServiceHandler { 
    static String response = null; 
    public final static int GET = 1; 
    public final static int POST = 2; 

    // Default Constructor 
    public ServiceHandler() { 
     // TODO Auto-generated constructor stub 
    } 

    public String makeServiceCall(String url, int method) { 
     return this.makeServiceCall(url, method, null); 
    } 

    public String makeServiceCall(String url, int method, String parameter) { 

     try { 
      // http client 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpEntity httpEntity = null; 
      HttpResponse httpResponse = null; 

      // Checking http request method type 
      if (method == POST) { 
       HttpPost httpPost = new HttpPost(url); 

       httpResponse = httpClient.execute(httpPost); 

      } else if (method == GET) { 
       // appending params to url 
       if (parameter != null) { 
        url += parameter; 
       } 
       HttpGet httpGet = new HttpGet(url); 
       httpResponse = httpClient.execute(httpGet); 
       Log.d("Parmaeter2",parameter); 

      } 
      httpEntity = httpResponse.getEntity(); 
      response = EntityUtils.toString(httpEntity); 

     } catch (Exception e){ 
       Log.d("Service Handler Error",e.toString()); 
     } 

     return response; 

    } 

} 

は、しかし、私は、すべてのWebサービス要求を処理するこのServiceHandlerClassを持っていますエラー

04-10 03:30:44.850: E/AndroidRuntime(5559): Caused by: java.lang.NoSuchMethodError: org.apache.http.impl.client.DefaultHttpClient.execute 
04-10 03:30:44.850: E/AndroidRuntime(5559):  at com.example.shoponchat.ServiceHandler.makeServiceCall(ServiceHandler.java:52) 

答えて

0

のHttpClientが廃止されている以下のhttpResponse = httpClient.execute(httpPost);

This is my async DoInbackground code 

    class DoInBackground extends AsyncTask<Void, Void, Void> 
    { 
     @Override 
     protected void onPreExecute() { 
      // TODO Auto-generated method stub 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(MainActivity.this); 
      pDialog.setMessage("Please Wait..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      // TODO Auto-generated method stub 
      ServiceHandler sh = new ServiceHandler(); 
      String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET,ParameterToPass); 
      Log.d("Response: ", "> " + jsonStr); 

      //PojoProduct item = null; 
      if (jsonStr != null) { 
       try { 
        JSONObject jsonObj = new JSONObject(jsonStr); 
        jsonarray = jsonObj.getJSONArray(TAG_CONTACTS); 

        for (int i = 0; i < jsonarray.length(); i++) { 
         JSONObject c = jsonarray.getJSONObject(i); 
         msg = c.getString(TAG_MESSAGE); 

        } 


       } catch (Exception e) { 
        // TODO: handle exception 
       } 
      } else { 

      } 


      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      // TODO Auto-generated method stub 
      super.onPostExecute(result); 

      if(!msg.equals("false")) 
      { 

       SharedPreferences.Editor editor = sharedpreferences.edit(); 

       editor.putString("Username", txtUserName.getText().toString().trim()); 
       editor.putString("Password", txtPassword.getText().toString().trim()); 
       editor.commit(); 

       Intent i=new Intent(MainActivity.this,Category.class); 
       finish(); 
       startActivity(i); 
       //System.out.println("Successful"); 
       //Toast.makeText(getBaseContext(),"SuccessFul", Toast.LENGTH_LONG).show(); 
      } 
      else 
      { 
       txtUserName.setText(""); 
       txtPassword.setText(""); 
       Toast.makeText(getBaseContext(),"Please Enter Valid UserName & Password.", Toast.LENGTH_LONG).show(); 
      } 
      pDialog.dismiss(); 
     } 

    } 

上のエラーを取得することは、それはuはHttpURLConnectionの.. の使用を開始する場合、私はuが理解するのを助けることができるコードを提供していますベストプラクティスでしょうuは、他の情報:)

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

    String url_ = "Provide url here"; 
    HttpURLConnection conn; 

    @Override 
    protected String doInBackground(Void... params) { 
     try { 
      URL url = new URL(url_); 

      conn = (HttpURLConnection) url.openConnection(); 
      conn.setReadTimeout(15000); 
      conn.setConnectTimeout(15000); 
      conn.setRequestMethod("POST"); 
      conn.setDoInput(true); 
      conn.setDoOutput(true); 

      OutputStream os = conn.getOutputStream(); 
      BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8")); 
      SharedPreferences userInfo = getSharedPreferences("mypref", 0); 
      String urlParameters = "username=" 
        + URLEncoder 
          .encode(userInfo.getString("username", "Null"), 
            "UTF-8"); 
      writer.write(urlParameters); 
      writer.flush(); 
      writer.close(); 
      os.close(); 

      int responseCode = conn.getResponseCode(); 

      if (responseCode == HttpURLConnection.HTTP_OK) { 

       BufferedReader bufferedReader = new BufferedReader(
         new InputStreamReader(conn.getInputStream())); 
       StringBuilder stringBuilder = new StringBuilder(); 
       String line; 
       while ((line = bufferedReader.readLine()) != null) { 
        stringBuilder.append(line + '\n'); 
       } 

       String jsonString = stringBuilder.toString(); 
       System.out.println(jsonString); 
       jsonArray = new JSONArray(jsonString); 

       return "User List Loaded succesfully"; 

      } else { 

       return "Error occured in Registration"; 

      } 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
      System.out.println("Exception1"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      System.out.println("Exception2"); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
      System.out.println("Exception3"); 
     } finally { 
      conn.disconnect(); 
     } 
     return "Null"; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     // TODO Auto-generated method stub 
     super.onPostExecute(result); 
     String[] names = new String[jsonArray.length()]; 
     for (int i = 0; i < jsonArray.length(); i++) { 
      try { 
       JSONObject jsonObject = jsonArray.getJSONObject(i); 
       String username = jsonObject.getString("username"); 
       names[i] = username; 
      } catch (JSONException e) { 
       e.printStackTrace(); 
       System.out.println("Json array exception"); 
      } 

     } 
    } 

} 
0

ファーストを必要とする場合は、HttpURLConnection .. 使用方法を掲載していません私はHTTPClientの使用を推奨しません。なぜなら、これはもうsdkバージョン23からサポートされていないからです。

したがって、ネットワーク操作をURL接続に移行する方がよいでしょう。

私はNetworkOps Utilを作成しました。あなたはそれがあなたのための任意の使用可能かどうか、その上を見てとることができます。

import android.content.Context; 
import android.net.Uri; 
import android.util.Log; 

import com.csehelper.variables.Constants; 
import com.csehelper.variables.Keys; 
import com.csehelper.variables.Url; 

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.net.HttpURLConnection; 
import java.net.ProtocolException; 
import java.net.SocketTimeoutException; 
import java.net.URL; 
import java.util.ArrayList; 

public class NetworkOps { 
    public final String EXCEPTION = "~Exception~"; 
    /**************************** 
    * Method to Grab Source 
    ****************************/ 
    public static String GrabSource(String URL) { 
     return PostData(URL, null); 
    } 



    /** 
    * ***************************************** 
    * Method to Grab Source code from URL 
    * Posting Data 
    * ***************************************** 
    */ 
    private static String PostData(String url, Uri.Builder uribuilder) { 
     String Source; 
     HttpURLConnection.setFollowRedirects(false); 
     HttpURLConnection urlConnection = null; 
     try { 
      urlConnection = (HttpURLConnection) new URL(url).openConnection(); 
      urlConnection.setDoOutput(true); 
      urlConnection.setConnectTimeout(10000); 

      if(uribuilder != null) { 
       String query = uribuilder.build().getEncodedQuery(); 

       OutputStream os = urlConnection.getOutputStream(); 
       BufferedWriter writer = new BufferedWriter(
         new OutputStreamWriter(os, "UTF-8")); 
       writer.write(query); 
       writer.flush(); 
       writer.close(); 
       os.close(); 
      } 

      urlConnection.connect(); 

      if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { 

       String line; 
       StringBuilder builder = new StringBuilder(); 
       InputStreamReader isr = new InputStreamReader(
         urlConnection.getInputStream()); 
       BufferedReader reader = new BufferedReader(isr); 
       while ((line = reader.readLine()) != null) { 
        builder.append(line); 
       } 
       Source = builder.toString(); 
      } else { 
       Source = EXCEPTION + "Server unreachable. Check network connection."; 
      } 
     } catch (SocketTimeoutException e) { 
      Source = EXCEPTION + "Connection timed out."; 
     } catch (java.net.UnknownHostException e) { 
      Source = EXCEPTION + Constants.EXCEPTION_NO_NET; 
     } catch (ArrayIndexOutOfBoundsException e) { 
      Source = EXCEPTION + "Server error"; 
     } catch (ProtocolException e) { 
      Source = EXCEPTION + "Protocol error"; 
     } catch (IOException e) { 
      Source = EXCEPTION + "Server unreachable. Check network connection."; 
     } catch (Exception e) { 
      Source = EXCEPTION + "Error:" + e.toString() + " - " 
        + e.getMessage(); 
      e.printStackTrace(); 

     } finally { 
      if (urlConnection != null) urlConnection.disconnect(); 
     } 
     return Source; 
    } 


} 

コールをこれらの静的関数AsyncTaskから:あなたはまた、機能PostDataのにデータを投稿することができ

/********************************* 
* AsyncTask to GrabSource 
********************************/ 
class AsyncTask_GrabSource extends AsyncTask<Void, Void, Void> { 

    String Source = null; 
    String url = "https://enigmatic-woodland-35608.herokuapp.com/pager.json"; 
    @Override 
    protected void onPreExecute() { 
     //Runs on Main Thread. You can access your UI elements here. 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     // Don't access any UI elements from this function 
     Source = NetworkOps.GrabSource(this.url); 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     if (Source != null) { 
      if (!Source.contains("~Exception~")) { 
       //Show Error Message or do whatever you want 
      } else { 
       //Do Whatever with your Grabbed Sourcecode. 
       // This function runs on UI Thread, so you can update UI elements here 
      } 

    } 
} 

。方法doInBackgroundでは、これを追加します。

Uri.Builder builder = new Uri.Builder() 
        .appendQueryParameter("key", "value") 
        .appendQueryParameter("key2", "value2"); 

Source = NetworkOps.PostData(getApplicationContext(), url, builder); 

アムいないことを確認localhostは:8080は、Android

を介してアクセスできます