有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法解析符号HttpPost

我尝试了所有可能的方法,但仍然出现以下错误- 1.无法解析符号ClientProtocolException 2.无法解析符号HttpPost 3.无法解析符号DefaultHttpClient

JSONParser。爪哇

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;

        }

主要活动。爪哇

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


   }

建造。格拉德尔

apply plugin: 'com.安卓.application'

  安卓 {
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-安卓.txt'), 'proguard-rules.pro'
    }
}


}

  dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.安卓.support:appcompat-v7:23.1.1'
compile 'com.安卓.support:design:22.2.0'
compile 'com.安卓.support:recyclerview-v7:22.2.1'
compile 'com.安卓.support:support-v4:23.0.0'
compile 'com.google.安卓.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:安卓="http://schemas.安卓.com/apk/res/安卓"
package="com.example.niki" >

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

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

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

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


共 (4) 个答案

  1. # 1 楼答案

    ApacheHttpClient已被弃用(并在android 6.0中被删除),因此您应该使用其他东西,比如android的内置HttpUrlConnection类,或者像OkHttpVolley这样的库,这是我的建议


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

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

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

  2. # 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);
    
  3. # 3 楼答案

    使用截击库代替See this

  4. # 4 楼答案

    我和maven也有同样的问题。我用了贝娄依赖。您可以使用相关的Gradle依赖项

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.1.1</version>
    </dependency>