Come aggiungere parametri a HttpURLConnection usando POST usando NameValuePair


257

Sto provando a fare POST con HttpURLConnection(devo usarlo in questo modo, non posso usare HttpPost) e vorrei aggiungere parametri a quella connessione come

post.setEntity(new UrlEncodedFormEntity(nvp));

dove

nvp = new ArrayList<NameValuePair>();

avendo alcuni dati memorizzati. Non riesco a trovare un modo per aggiungere questo ArrayListal mio HttpURLConnectionche è qui:

HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);

Il motivo di quella scomoda combinazione https e http è la necessità di non verificare il certificato. Questo non è un problema, tuttavia, registra bene il server. Ma ne ho bisogno per pubblicare con argomenti.

Qualche idea?


Disclaimer duplicato:

Nel 2012, non avevo idea di come i parametri fossero stati inseriti in una richiesta POST HTTP . Mi stavo aggrappando NameValuePairperché era in un tutorial. Questa domanda potrebbe sembrare un duplicato, tuttavia, la mia auto del 2012 ha letto quell'altra domanda e NON stava usando NameValuePair. In realtà, non ha risolto il mio problema.


2
In caso di problemi con la pubblicazione dei parametri, il link seguente potrebbe essere di aiuto. stackoverflow.com/questions/2793150/…
— Hitendra

1
String url = " example.com "; String charset = "UTF-8"; String param1 = "value1"; String param2 = "value2"; // ... String query = String.format ("param1 =% s & param2 =% s", URLEncoder.encode (param1, charset), URLEncoder.encode (param2, charset)); è possibile creare una stringa di query anziché utilizzare l'elenco NameValuePair.
— Hitendra,

"Ho bisogno di usarlo in questo modo, non posso usare HttpPost" ecco perché ho suggerito che questa altra risposta pubblicata da Manikandan funzioni bene.
— Hitendra,


1
Fu perché "molte delle risposte" qui erano le stesse delle risposte a quella domanda. Ma ora vedo che è una domanda diversa, grazie per il chiarimento :)
— rogerdpack

Risposte:


362

È possibile ottenere il flusso di output per la connessione e scrivere la stringa di query dei parametri su di essa.

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

conn.connect();

...

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

25
NameValuePair può essere sostituito anche con SimpleEntry di AbstractMap. Vedere questa pagina: stackoverflow.com/questions/2973041/a-keyvaluepair-in-java

Ecco le importazioni se non sei sicuro. import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair;
— WoodenKitty,

9
Per prestazioni ottimali, è necessario chiamare setFixedLengthStreamingMode (int) quando la lunghezza del corpo è nota in anticipo o setChunkedStreamingMode (int) quando non lo è. Altrimenti HttpURLConnection sarà costretto a bufferizzare l'intero corpo della richiesta in memoria prima che venga trasmesso, sprecando (e possibilmente esaurendo) l'heap e aumentando la latenza.
— Muhammad Babar,

11
NameValuePair è deprecato in Api 22, controlla la mia risposta stackoverflow.com/a/29561084/4552938
— Fahim

1
Forse puoi usare la modalità raw quando costruisci un oggetto URL, qualcosa del genere: URL url = new URL("http://yoururl.com?k1=v1&k2=v2&···&kn=vn");quando impostato conn per usare il metodo POST non è necessario scriverli.
— alexscmar,

184

Poiché NameValuePair è obsoleto. Pensato di condividere il mio codice

public String  performPostCall(String requestURL,
            HashMap<String, String> postDataParams) {

        URL url;
        String response = "";
        try {
            url = new URL(requestURL);

            HttpURLConnection 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"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line=br.readLine()) != null) {
                    response+=line;
                }
            }
            else {
                response="";

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

        return response;
    }

....

  private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }

10
Grazie per tenerlo aggiornato Fahim :-)
— Michal

3
Se compileSdkVersion è 23 (Marshmallow) non è più possibile utilizzare NameValuePair perché hanno rimosso la libreria. Temevo che la migrazione sarebbe stata una seccatura ma la tua soluzione mi ha fatto risparmiare un sacco di tempo. Grazie.
— Sfida accettata

Funziona benissimo, ma perché la risposta ha virgolette doppie, come ""result"" ?
— Apostrofix,

1
Qualcuno di voi ha avuto un problema con questa riga OutputStream os = conn.getOutputStream();sul jelly bean per quanto riguarda nessun indirizzo associato al nome host?
— Ricardo

1
Grazie per aver condiviso il tuo codice. Anche il sito Web degli sviluppatori Android non offre una soluzione.
— Ahsan

153

Se non ti serve ArrayList<NameValuePair> parametri for, questa è una soluzione più breve che crea la stringa di query usando la Uri.Builderclasse:

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

Uri.Builder builder = new Uri.Builder()
        .appendQueryParameter("firstParam", paramValue1)
        .appendQueryParameter("secondParam", paramValue2)
        .appendQueryParameter("thirdParam", paramValue3);
String query = builder.build().getEncodedQuery();

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

conn.connect();

7
questa dovrebbe essere una risposta, in quanto non è necessario fare un nuovo inventario della ruota!
— injecteer,

come caricare filebody in appendqueryparameter per le immagini e tutto il resto
— Harsha il

2
soluzione più soddisfacente
— PYPL

@mpolci, ho una domanda / dubbio riguardo al tipo complesso di parametri. Ho dei parametri e non so come passarli. {"chiave1": "valore1", "chiave2": "valore2", "chiave3": {"chiave interna1": "valore interno1", "chiave interna2": "valore interno 2"}}. Mi è stato fornito questo tipo di parametri chiave complessi e voglio sapere come posso passare questi parametri nel servizio web?
— Krups

1
@Krups Penso che il tuo problema sia diverso da questo, prova a cercare l'invio di oggetti JSON usando POST
— mpolci,

25

Una soluzione è creare la tua stringa di parametri.

Questo è il metodo effettivo che ho usato per il mio ultimo progetto. Devi cambiare args da hashtable a namevaluepair's:

private static String getPostParamString(Hashtable<String, String> params) {
    if(params.size() == 0)
        return "";

    StringBuffer buf = new StringBuffer();
    Enumeration<String> keys = params.keys();
    while(keys.hasMoreElements()) {
        buf.append(buf.length() == 0 ? "" : "&");
        String key = keys.nextElement();
        buf.append(key).append("=").append(params.get(key));
    }
    return buf.toString();
}

INSERIMENTO dei parametri:

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(getPostParamString(req.getPostParams()));

3
Sicuramente dovresti codificare le coppie chiave-valore
— Max Nanasy,

14

Penso di aver trovato esattamente ciò di cui hai bisogno. Potrebbe aiutare gli altri.

È possibile utilizzare il metodo UrlEncodedFormEntity.writeTo (OutputStream) .

UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvp); 
http.connect();

OutputStream output = null;
try {
  output = http.getOutputStream();    
  formEntity.writeTo(output);
} finally {
 if (output != null) try { output.close(); } catch (IOException ioe) {}
}

14

La risposta accettata genera un ProtocolException a:

OutputStream os = conn.getOutputStream();

perché non abilita l'output per l'oggetto URLConnection. La soluzione dovrebbe includere questo:

conn.setDoOutput(true);

per farlo funzionare.


13

Se non è troppo tardi, vorrei condividere il mio codice

Utils.java:

public static String buildPostParameters(Object content) {
        String output = null;
        if ((content instanceof String) ||
                (content instanceof JSONObject) ||
                (content instanceof JSONArray)) {
            output = content.toString();
        } else if (content instanceof Map) {
            Uri.Builder builder = new Uri.Builder();
            HashMap hashMap = (HashMap) content;
            if (hashMap != null) {
                Iterator entries = hashMap.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
                    entries.remove(); // avoids a ConcurrentModificationException
                }
                output = builder.build().getEncodedQuery();
            }
        }

        return output;
    }

public static URLConnection makeRequest(String method, String apiAddress, String accessToken, String mimeType, String requestBody) throws IOException {
        URL url = new URL(apiAddress);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(!method.equals("GET"));
        urlConnection.setRequestMethod(method);

        urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken);        

        urlConnection.setRequestProperty("Content-Type", mimeType);
        OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
        writer.write(requestBody);
        writer.flush();
        writer.close();
        outputStream.close();            

        urlConnection.connect();

        return urlConnection;
    }

MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new APIRequest().execute();
}

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

        @Override
        protected Object doInBackground(Void... params) {

            // Of course, you should comment the other CASES when testing one CASE

            // CASE 1: For FromBody parameter
            String url = "http://10.0.2.2/api/frombody";
            String requestBody = Utils.buildPostParameters("'FromBody Value'"); // must have '' for FromBody parameter
            HttpURLConnection urlConnection = null;
            try {
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);                    
                InputStream inputStream;
                // get stream
                if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                    inputStream = urlConnection.getInputStream();
                } else {
                    inputStream = urlConnection.getErrorStream();
                }
                // parse stream
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String temp, response = "";
                while ((temp = bufferedReader.readLine()) != null) {
                    response += temp;
                }
                return response;
            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }

            // CASE 2: For JSONObject parameter
            String url = "http://10.0.2.2/api/testjsonobject";
            JSONObject jsonBody;
            String requestBody;
            HttpURLConnection urlConnection;
            try {
                jsonBody = new JSONObject();
                jsonBody.put("Title", "BNK Title");
                jsonBody.put("Author", "BNK");
                jsonBody.put("Date", "2015/08/08");
                requestBody = Utils.buildPostParameters(jsonBody);
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);                    
                ...
                // the same logic to case #1
                ...
                return response;
            } catch (JSONException | IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }           

            // CASE 3: For form-urlencoded parameter
            String url = "http://10.0.2.2/api/token";
            HttpURLConnection urlConnection;
            Map<String, String> stringMap = new HashMap<>();
            stringMap.put("grant_type", "password");
            stringMap.put("username", "username");
            stringMap.put("password", "password");
            String requestBody = Utils.buildPostParameters(stringMap);
            try {
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/x-www-form-urlencoded", requestBody);
                ...
                // the same logic to case #1
                ...
                return response;
            } catch (Exception e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }                  
        }

        @Override
        protected void onPostExecute(String response) {
            super.onPostExecute(response);
            // do something...
        }
    }

@Srinivasan come vedi nel mio codice: "if (urlConnection.getResponseCode () == HttpURLConnection.HTTP_OK) {...} else {...}"
— BNK

Sì, l'ho già
— capito,

1
@Srinivasan maggiori dettagli puoi provare InputStream inputStream = null; if (urlConnection.getResponseCode () == HttpURLConnection.HTTP_OK) {inputStream = urlConnection.getInputStream (); } else {inputStream = urlConnection.getErrorStream (); }
— BNK,

@Srinivasan in realtà, se risp. Codice <400 (Bad Request), si utilizza getInputStream, se> = 400, getErrorStream
— BNK

1
Super Stuff Bro Buoni esempi
— Cosa succede il

10

C'è un approccio molto più semplice usando PrintWriter (vedi qui )

Fondamentalmente tutto ciò che serve è:

// set up URL connection
URL urlToRequest = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection)urlToRequest.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// write out form parameters
String postParamaters = "param1=value1&param2=value2"
urlConnection.setFixedLengthStreamingMode(postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters);
out.close();

// connect
urlConnection.connect();

4

AsyncTaskper inviare i dati come JSONObecttramite il POSTmetodo

public class PostMethodDemo extends AsyncTask<String , Void ,String> {
        String server_response;

        @Override
        protected String doInBackground(String... strings) {
            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(strings[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                urlConnection.setDoInput(true);
                urlConnection.setRequestMethod("POST");

                DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream ());

                try {
                    JSONObject obj = new JSONObject();
                    obj.put("key1" , "value1");
                    obj.put("key2" , "value2");

                    wr.writeBytes(obj.toString());
                    Log.e("JSON Input", obj.toString());
                    wr.flush();
                    wr.close();
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
                urlConnection.connect();

                int responseCode = urlConnection.getResponseCode();

                if(responseCode == HttpURLConnection.HTTP_OK){
                    server_response = readStream(urlConnection.getInputStream());
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.e("Response", "" + server_response);
        }
    }

    public static String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }

3

Prova questo:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your url");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("user_name", "Name"));
nameValuePairs.add(new BasicNameValuePair("pass","Password" ));
nameValuePairs.add(new BasicNameValuePair("user_email","email" ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

String ret = EntityUtils.toString(response.getEntity());
Log.v("Util response", ret);

Puoi aggiungerne tutti nameValuePairsquanti ne hai bisogno. E non dimenticare di menzionare il conteggio nell'elenco.


fai riferimento a questo link. xyzws.com/Javafaq/...
— Manikandan

1
Questo non risponde alla domanda intitolata How to add parameters to HttpURLConnection using POST- Inganna.
— Utente3

2
Questa non è una risposta adeguata a questa domanda.
— Skynet,

1
NameValuePair è deprecato in Api 22, controlla la mia risposta stackoverflow.com/a/29561084/4552938
— Fahim

2

Per chiamare metodi POST / PUT / DELETE / GET Restful con intestazione personalizzata o dati json è possibile utilizzare la seguente classe Async

public class HttpUrlConnectionUtlity extends AsyncTask<Integer, Void, String> {
private static final String TAG = "HttpUrlConnectionUtlity";
Context mContext;
public static final int GET_METHOD = 0,
        POST_METHOD = 1,
        PUT_METHOD = 2,
        HEAD_METHOD = 3,
        DELETE_METHOD = 4,
        TRACE_METHOD = 5,
        OPTIONS_METHOD = 6;
HashMap<String, String> headerMap;

String entityString;
String url;
int requestType = -1;
final String timeOut = "TIMED_OUT";

int TIME_OUT = 60 * 1000;

public HttpUrlConnectionUtlity (Context mContext) {
    this.mContext = mContext;
    this.callback = callback;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(Integer... params) {
    int requestType = getRequestType();
    String response = "";
    try {


        URL url = getUrl();
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection = setRequestMethod(urlConnection, requestType);
        urlConnection.setConnectTimeout(TIME_OUT);
        urlConnection.setReadTimeout(TIME_OUT);
        urlConnection.setDoOutput(true);
        urlConnection = setHeaderData(urlConnection);
        urlConnection = setEntity(urlConnection);

        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            response = readResponseStream(urlConnection.getInputStream());
            Logger.v(TAG, response);
        }
        urlConnection.disconnect();
        return response;


    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (SocketTimeoutException e) {
        return timeOut;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        Logger.e(TAG, "ALREADY CONNECTED");
    }
    return response;
}

@Override
protected void onPostExecute(String response) {
    super.onPostExecute(response);

    if (TextUtils.isEmpty(response)) {
        //empty response
    } else if (response != null && response.equals(timeOut)) {
        //request timed out 
    } else    {
    //process your response
   }
}


private String getEntityString() {
    return entityString;
}

public void setEntityString(String s) {
    this.entityString = s;
}

private String readResponseStream(InputStream in) {
    BufferedReader reader = null;
    StringBuffer response = new StringBuffer();
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return response.toString();
}

private HttpURLConnection setEntity(HttpURLConnection urlConnection) throws IOException {
    if (getEntityString() != null) {
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(getEntityString());
        writer.flush();
        writer.close();
        outputStream.close();
    } else {
        Logger.w(TAG, "NO ENTITY DATA TO APPEND ||NO ENTITY DATA TO APPEND ||NO ENTITY DATA TO APPEND");
    }
    return urlConnection;
}

private HttpURLConnection setHeaderData(HttpURLConnection urlConnection) throws UnsupportedEncodingException {
    urlConnection.setRequestProperty("Content-Type", "application/json");
    urlConnection.setRequestProperty("Accept", "application/json");
    if (getHeaderMap() != null) {
        for (Map.Entry<String, String> entry : getHeaderMap().entrySet()) {
            urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    } else {
        Logger.w(TAG, "NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND");
    }
    return urlConnection;
}

private HttpURLConnection setRequestMethod(HttpURLConnection urlConnection, int requestMethod) {
    try {
        switch (requestMethod) {
            case GET_METHOD:
                urlConnection.setRequestMethod("GET");
                break;
            case POST_METHOD:
                urlConnection.setRequestMethod("POST");
                break;
            case PUT_METHOD:
                urlConnection.setRequestMethod("PUT");
                break;
            case DELETE_METHOD:
                urlConnection.setRequestMethod("DELETE");
                break;
            case OPTIONS_METHOD:
                urlConnection.setRequestMethod("OPTIONS");
                break;
            case HEAD_METHOD:
                urlConnection.setRequestMethod("HEAD");
                break;
            case TRACE_METHOD:
                urlConnection.setRequestMethod("TRACE");
                break;
        }
    } catch (ProtocolException e) {
        e.printStackTrace();
    }
    return urlConnection;
}

public int getRequestType() {
    return requestType;
}

public void setRequestType(int requestType) {
    this.requestType = requestType;
}

public URL getUrl() throws MalformedURLException {
    return new URL(url);
}

public void setUrl(String url) {
    this.url = url;
}

public HashMap<String, String> getHeaderMap() {
    return headerMap;
}

public void setHeaderMap(HashMap<String, String> headerMap) {
    this.headerMap = headerMap;
}   }

E l'uso è

    HttpUrlConnectionUtlity httpMethod = new HttpUrlConnectionUtlity (mContext);
    JSONObject jsonEntity = new JSONObject();

    try {
        jsonEntity.put("key1", value1);
        jsonEntity.put("key2", value2);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    httpMethod.setUrl(YOUR_URL_STRING);
    HashMap<String, String> headerMap = new HashMap<>();
    headerMap.put("key",value);
    headerMap.put("key1",value1);
    httpMethod.setHeaderMap(headerMap);
    httpMethod.setRequestType(WiseConnectHttpMethod.POST_METHOD); //specify POST/GET/DELETE/PUT
    httpMethod.setEntityString(jsonEntity.toString());
    httpMethod.execute();

1

Utilizzando org.apache.http.client.HttpClient puoi anche farlo facilmente con un modo più leggibile come di seguito.

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

All'interno di catch catch è possibile inserire

// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

1
Grazie per la risposta! Non posso usarlo in questo modo (indicato nella domanda, prima riga).
— Michal,

7
Questa non è una risposta adeguata a questa domanda.
— Skynet,

3
NameValuePair è deprecato in Api 22, controlla la mia risposta stackoverflow.com/a/29561084/4552938
— Fahim

1
Anche l'HTTP Client è stato deprecato e rimosso in api 23
— RevanthKrishnaKumar V.

0

Nel mio caso ho creato una funzione come questa per effettuare la richiesta Post che accetta l'URL String e l'hashmap dei parametri

 public  String postRequest( String mainUrl,HashMap<String,String> parameterList)
{
    String response="";
    try {
        URL url = new URL(mainUrl);

        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> param : parameterList.entrySet())
        {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        byte[] postDataBytes = postData.toString().getBytes("UTF-8");




        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        StringBuilder sb = new StringBuilder();
        for (int c; (c = in.read()) >= 0; )
            sb.append((char) c);
        response = sb.toString();


    return  response;
    }catch (Exception excep){
        excep.printStackTrace();}
    return response;
}

0

Uso qualcosa del genere:

SchemeRegistry sR = new SchemeRegistry();
sR.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

HttpParams params = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(params, sR);

HttpClient httpclient = new DefaultHttpClient(mgr, params);

HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);

-1
JSONObject params = new JSONObject();
try {
   params.put(key, val);
}catch (JSONException e){
   e.printStackTrace();
}

è così che passo "params" (JSONObject) tramite POST

connection.getOutputStream().write(params.toString().getBytes("UTF-8"));
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.