无法解析符号HttpPost

时间:2016-04-15 17:43:57

标签: java android json http-post

我尝试了一切,但我仍然遇到以下错误 - 1.Cannot解析符号ClientProtocolException 2.无法解析符号HttpPost 3.Cannot解析符号DefaultHttpClient

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>

4 个答案:

答案 0 :(得分:2)

不推荐使用HttpClient。我为网络操作创建了一个类,包括POST。试试这个:

从onCreate运行new AsyncTask_GrabSource().execute();;

我在我的项目中使用了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);

答案 1 :(得分:1)

使用排球库代替See this

答案 2 :(得分:1)

Apache HttpClient已被弃用(并从Android 6.0开始删除),因此您应该使用其他内容,例如Android内置的pub = d2i_RSA_PUBKEY(NULL, &public_key_buf, size); 类或类似OkHttpVolley的库这是我推荐的。

但是,您仍然可以将旧的Apache HttpClient作为库添加到项目中,方法是将HttpUrlConnection添加到org.apache.http.legacy,如下所示:

build.gradle

我不建议这样做,因为不再支持,我建议使用不同的HTTP客户端,如上所述。如果这有帮助,请告诉我。

答案 3 :(得分:0)

我和maven有同样的问题。我用下面的依赖。您可以使用相关的Gradle依赖。

duration_in_traffic("C/2")