2016-04-15 16 views
1

私は、可能なすべてのものを試してみましたが、私はまだ、次のエラーを取得しています - 1.Cannot解決シンボルClientProtocolException 2.Cannotの解決のシンボルHttpPost 3.Cannot解決シンボルDefaultHttpClientがシンボルを解決できませんHttpPost

をJSONParser.java

public class JSONParser { 
static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 

// constructor 
public JSONParser() { 

} 

public JSONObject getJSONFromUrl(String urlString) throws JSONException { 

    // Making HTTP request 
    try{ 
     // defaultHttpClient 

    HttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 

     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 

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

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "n"); 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // return JSON String 
    return jObj; 

     } 

MainActivity.java

public class contactsmap extends Fragment { 
private static String url = "A URL"; 
private static final String TAG_USER = "user"; 
private static final String TAG_ID = "id"; 
private static final String TAG_NAME = "name"; 
private static final String TAG_EMAIL = "email"; 

JSONArray user = null; 

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.contactsmap, container, false); 
    JSONParser jParser = new JSONParser(); 
    JSONObject json = null; 
    // Getting JSON from URL 
    try { 
     json = jParser.getJSONFromUrl(url); 
    } 
    catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    try { 
     // Getting JSON Array 
     user = json.getJSONArray(TAG_USER); 
     JSONObject c = user.getJSONObject(0); 

     // Storing JSON item in a Variable 
     String id = c.getString(TAG_ID); 
     String name = c.getString(TAG_NAME); 
     String email = c.getString(TAG_EMAIL); 

     //Importing TextView 
     final TextView uid = (TextView)v.findViewById(R.id.textView1); 

     //Set JSON Data in TextView 
     uid.setText(id); 

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




    return v; 
} 


    } 

build.gradle

apply plugin: 'com.android.application' 

    android { 
compileSdkVersion 23 
buildToolsVersion "23.0.0" 
useLibrary 'org.apache.http.legacy' 

defaultConfig { 
    applicationId "com.example.niki" 
    minSdkVersion 8 
    targetSdkVersion 23 
    versionCode 1 
    versionName "1.0" 
} 
buildTypes { 
    release { 
     minifyEnabled false 
     proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
    } 
} 


} 

    dependencies { 
compile fileTree(dir: 'libs', include: ['*.jar']) 
compile 'com.android.support:appcompat-v7:23.1.1' 
compile 'com.android.support:design:22.2.0' 
compile 'com.android.support:recyclerview-v7:22.2.1' 
compile 'com.android.support:support-v4:23.0.0' 
compile 'com.google.android.gms:play-services:+' 
compile 'org.apache.httpcomponents:httpclient:4.2.6' 
compile 'org.apache.httpcomponents:httpmime:4.2.6' 
compile files('libs/core.jar') 

}

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.example.niki" > 

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

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

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name=".Swipe" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    </application> 

マニフェスト

+0

https://stackoverflow.com/questions/32949626/org-apache-http-entity-fileentity-is-deprecated-in-android-6-marshmallow – CommonsWare

+1

のApache HttpClientをあります他のものを使うことができます。 – JonasCz

+0

代わりにボレーを使用してください。ずっと簡単。 – driftking9987

答えて

1

はApacheのHttpClientは非推奨(とAndroid 6.0のように除去される)を使用ボレーライブラリだからあなたは他の何かを使うべきです、たとえば、AndroidのHttpUrlConnectionクラス、またはまたはVolleyのようなライブラリを使用することをお勧めします。


しかし、あなたはまだあなたのプロジェクトにレガシー、古いApacheのHttpClientを追加することができ、ライブラリとして、あなたのbuild.gradleorg.apache.http.legacyを追加することによって、次のように:

android { 
    useLibrary 'org.apache.http.legacy' 
} 

私はこれを行うことはお勧めしません以降はサポートされなくなりました。上記のように、代わりに別のHTTPクライアントを使用することをおすすめします。これが役に立ったら教えてください。

2

HttpClientは推奨されていません。私は、POSTを含むネットワーク操作用のクラスを作成しました。試してみてください:

ただ実行new AsyncTask_GrabSource().execute();からonCreate;

私は自分のプロジェクトでNetworkOpsユーティリティを使用しています。それを試してみてください。

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からこれらの静的関数を呼び出します。

/********************************* 
* 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 

//Add your code here : 
try { 
     json = jParser.getJSONFromUrl(url); 
    } 
    catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    try { 
     // Getting JSON Array 
     user = json.getJSONArray(TAG_USER); 
     JSONObject c = user.getJSONObject(0); 

     // Storing JSON item in a Variable 
     String id = c.getString(TAG_ID); 
     String name = c.getString(TAG_NAME); 
     String email = c.getString(TAG_EMAIL); 

     //Importing TextView 
     final TextView uid = (TextView)v.findViewById(R.id.textView1); 

     //Set JSON Data in TextView 
     uid.setText(id); 

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

    } 
} 

をまた機能PostDataの持つデータを投稿することができます。方法doInBackgroundでは、これを追加します。

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

Source = NetworkOps.PostData(getApplicationContext(), url, builder); 
関連する問題