2016-04-15 8 views
1

Ich habe versucht, alles möglich, aber ich bin immer noch die folgenden Fehler bekommen - 1.Cannot resolve symbol ClientProtocolException 2.Cannot Entschlossenheit Symbol Httppost 3.Cannot Entschlossenheit Symbol DefaultHttpClientKann nicht Symbol lösen 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') 

}

manifest

<?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 ist veraltet, könnten Sie etwas anderes verwenden. – JonasCz

+0

Verwenden Sie stattdessen Volley. Viel einfacher. – driftking9987

Antwort

1

Verwenden Volley Bibliothek statt See this

1

Apache Httpclient veraltet ist (und wie von Android 6.0 entfernt), Sie sollten also etwas anderes verwenden, wie zum Beispiel Android HttpUrlConnection Klassen oder eine Bibliothek wie OkHttp oder Volley, was ich empfehlen würde.


Sie können jedoch immer noch das Erbe, alte Apache Httpclient zu Ihrem Projekt als Bibliothek hinzufügen, indem org.apache.http.legacy zu Ihrem build.gradle hinzufügen, wie folgt aus:

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

Ich würde nicht empfehlen, dies zu tun , seit wird es nicht mehr unterstützt, und ich würde empfehlen, stattdessen einen anderen HTTP-Client, wie oben erwähnt. Lassen Sie mich wissen, ob das hilft.

2

HttpClient ist veraltet. Ich hatte eine Klasse für Netzwerkoperationen erstellt, einschließlich POST. Versuchen Sie Folgendes:

einfach new AsyncTask_GrabSource().execute(); von onCreate ausführen;

Ich verwende ein NetworkOps util in meinen Projekten. Versuchen Sie es:

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; 
    } 


} 

Rufen Sie diese statischen Funktionen von 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(); 
    } 
      } 

    } 
} 

Sie auch Daten mit der Funktion Postdata veröffentlichen können. In Verfahren doInBackground, fügen Sie diese:

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

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