Android的GET和POST请求(Android GET and POST Request)

2019-07-30 23:23发布

任何人都可以指向我一个很好的执行的方法来发送GET和POST请求。 他们很多的方法可以做到这些,我寻找最好的实现。 其次是有送这两种方法,而然后用两种不同的方式的通用方式。 所有的GET方法后只是在查询字符串参数,可以而POST方法使用的PARAMS头。

谢谢。

Answer 1:

您可以使用HttpURLConnection (java.net中)类发送POST或GET HTTP请求。 这是一样的,可能要发送一个HTTP请求任何其他应用程序。 该代码发送HTTP请求是这样的:

import java.net.*;
import java.io.*;
public class SendPostRequest {
  public static void main(String[] args) throws MalformedURLException, IOException {
    URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
    HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
    String post = "this will be the post data that you will send"
    request.setDoOutput(true);
    request.addRequestProperty("Content-Length", Integer.toString(post.length)); //add the content length of the post data
    request.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //add the content type of the request, most post data is of this type
    request.setMethod("POST");
    request.connect();
    OutputStreamWriter writer = new OutputStreamWriter(request.getOutputStream()); //we will write our request data here
    writer.write(post);
    writer.flush();
  }
}

GET请求看起来有点不同,但大部分的代码是一样的。 你不必担心做输出,流或指定的内容长度或者内容类型:

import java.net.*;
import java.io.*;

public class SendPostRequest {
  public static void main(String[] args) throws MalformedURLException, IOException {
    URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
    HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
    request.setMethod("GET");
    request.connect();

  }
}


Answer 2:

我更喜欢使用专用类做GET / POST和任何HTTP连接或请求。 而且我用HttpClient执行这些GET / POST方法。

下面是我的项目样本。 我需要线程安全的执行,以便有ThreadSafeClientConnManager

存在使用GET(fetchData)和POST的一个例子(sendOrder)

正如你所看到execute的一般方法执行HttpUriRequest -它可以是POST或GET。

public final class ClientHttpClient {

private static DefaultHttpClient client;
private static CookieStore cookieStore;
private static HttpContext httpContext;

static {
    cookieStore = new BasicCookieStore();
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    client = getThreadSafeClient();
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, AppConstants.CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, AppConstants.SOCKET_TIMEOUT);
    client.setParams(params);
}

private static DefaultHttpClient getThreadSafeClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    ClientConnectionManager mgr = client.getConnectionManager();
    HttpParams params = client.getParams();
    client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()),
            params);
    return client;
}

private ClientHttpClient() {
}

public static String execute(HttpUriRequest http) throws IOException {
    BufferedReader reader = null;
    try {
        StringBuilder builder = new StringBuilder();
        HttpResponse response = client.execute(http, httpContext);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        reader = new BufferedReader(new InputStreamReader(content, CHARSET));
        String line = null;
        while((line = reader.readLine()) != null) {
            builder.append(line);
        }

        if(statusCode != 200) {
            throw new IOException("statusCode=" + statusCode + ", " + http.getURI().toASCIIString()
                    + ", " + builder.toString());
        }

        return builder.toString();
    }
    finally {
        if(reader != null) {
            reader.close();
        }
    }
}


public static List<OverlayItem> fetchData(Info info) throws JSONException, IOException {
    List<OverlayItem> out = new LinkedList<OverlayItem>();
    HttpGet request = buildFetchHttp(info);
    String json = execute(request);
    if(json.trim().length() <= 2) {
        return out;
    }
    try {
        JSONObject responseJSON = new JSONObject(json);
        if(responseJSON.has("auth_error")) {
            throw new IOException("auth_error");
        }
    }
    catch(JSONException e) {
        //ok there was no error, because response is JSONArray - not JSONObject
    }

    JSONArray jsonArray = new JSONArray(json);
    for(int i = 0; i < jsonArray.length(); i++) {
        JSONObject chunk = jsonArray.getJSONObject(i);
        ChunkParser parser = new ChunkParser(chunk);
        if(!parser.hasErrors()) {
            out.add(parser.parse());
        }
    }
    return out;
}

private static HttpGet buildFetchHttp(Info info) throws UnsupportedEncodingException {
    StringBuilder builder = new StringBuilder();
    builder.append(FETCH_TAXIS_URL);
    builder.append("?minLat=" + URLEncoder.encode("" + mapBounds.getMinLatitude(), ENCODING));
    builder.append("&maxLat=" + URLEncoder.encode("" + mapBounds.getMaxLatitude(), ENCODING));
    builder.append("&minLon=" + URLEncoder.encode("" + mapBounds.getMinLongitude(), ENCODING));
    builder.append("&maxLon=" + URLEncoder.encode("" + mapBounds.getMaxLongitude(), ENCODING));
    HttpGet get = new HttpGet(builder.toString());
    return get;
}

public static int sendOrder(OrderInfo info) throws IOException {
    HttpPost post = new HttpPost(SEND_ORDER_URL);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("id", "" + info.getTaxi().getId()));
    nameValuePairs.add(new BasicNameValuePair("address", info.getAddressText()));
    nameValuePairs.add(new BasicNameValuePair("name", info.getName()));
    nameValuePairs.add(new BasicNameValuePair("surname", info.getSurname()));
    nameValuePairs.add(new BasicNameValuePair("phone", info.getPhoneNumber()));
    nameValuePairs.add(new BasicNameValuePair("passengers", "" + info.getPassengers()));
    nameValuePairs.add(new BasicNameValuePair("additionalDetails", info.getAdditionalDetails()));
    nameValuePairs.add(new BasicNameValuePair("lat", "" + info.getOrderLocation().getLatitudeE6()));
    nameValuePairs.add(new BasicNameValuePair("lon", "" + info.getOrderLocation().getLongitudeE6()));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    String response = execute(post);
    if(response == null || response.trim().length() == 0) {
        throw new IOException("sendOrder_response_empty");
    }

    try {
        JSONObject json = new JSONObject(response);
        int orderId = json.getInt("orderId");
        return orderId;
    }
    catch(JSONException e) {
        throw new IOException("sendOrder_parsing: " + response);
    }
}

编辑

execute ,因为有时我使用自定义(或动态)GET / POST请求的方法是公开的。

如果您有URL对象,你可以传递给execute方法:

HttpGet request = new HttpGet(url.toString());
execute(request);


Answer 3:

至于你说:一开始的参数是在URL中 - 所以,你可以使用网页视图一个使用loadURL()来发送。

[..].loadUrl("http://www.example.com/data.php?param1=value1&param2=value2&...");


Answer 4:

开发人员培训文档有一个对GET请求很好的例子 。 你是负责添加查询参数的URL。

邮政是相似的,但正如你所说的,完全不同的。 该HttpConnectionURLConnection类都可以做,而且很容易刚才设置的后机身采用的输出流。



Answer 5:

 protected String doInBackground(String... strings) {
        String response = null;
        String data = null;
        try {
            data = URLEncoder.encode("CustomerEmail", "UTF-8")
                    + "=" + URLEncoder.encode(username, "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = Constant.URL_FORGOT_PASSWORD;// this is url 
        response = ServiceHandler.postData(url,data);
        if (response.equals("")){
            return response;
        }else {
            return response;
        }

    }


public static String postData(String urlpath,String data){

    String text = "";
    BufferedReader reader=null;
    try
    {
        // Defined URL  where to send data
        URL url = new URL(urlpath);

        // Send POST data request
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write( data );
        wr.flush();

        // Get the server response
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        text = sb.toString();
        return text;
    }
    catch(Exception ex)
    {
    }
    finally
    {
        try
        {
            reader.close();
        }
        catch(Exception ex) {}
    }
    return text;
}


Answer 6:

private RequestListener listener;
private int requestId;
private HashMap<String, String> reqParams;
private File file;
private String fileName;
private RequestMethod reqMethod;
private String url;
private Context context;
private boolean isProgressVisible = false;
private MyProgressDialog progressDialog;

public NetworkClient(Context context, int requestId, RequestListener listener,
                     String url, HashMap<String, String> reqParams, RequestMethod reqMethod,
                     boolean isProgressVisible) {

    this.listener = listener;
    this.requestId = requestId;
    this.reqParams = reqParams;
    this.reqMethod = reqMethod;
    this.url = url;
    this.context = context;
    this.isProgressVisible = isProgressVisible;
}

public NetworkClient(Context context, int requestId, RequestListener listener,
                     String url, HashMap<String, String> reqParams, File file, String fileName, RequestMethod reqMethod,
                     boolean isProgressVisible) {

    this.listener = listener;
    this.requestId = requestId;
    this.reqParams = reqParams;
    this.file = file;
    this.fileName = fileName;
    this.reqMethod = reqMethod;
    this.url = url;
    this.context = context;
    this.isProgressVisible = isProgressVisible;
}

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

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

    try {

        if (Utils.isInternetAvailable(context)) {

            OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
            clientBuilder.connectTimeout(10, TimeUnit.SECONDS);
            clientBuilder.writeTimeout(10, TimeUnit.SECONDS);
            clientBuilder.readTimeout(20, TimeUnit.SECONDS);
            OkHttpClient client = clientBuilder.build();

            if (reqMethod == RequestMethod.GET) {

                Request.Builder reqBuilder = new Request.Builder();
                reqBuilder.url(url);
                Request request = reqBuilder.build();
                Response response = client.newCall(request).execute();
                String message = response.message();
                String res = response.body().string();

                JSONObject jObj = new JSONObject();
                jObj.put("statusCode", 1);
                jObj.put("response", message);
                return jObj.toString();

            } else if (reqMethod == RequestMethod.POST) {


                FormBody.Builder formBuilder = new FormBody.Builder();

                RequestBody body = formBuilder.build();

                Request.Builder reqBuilder = new Request.Builder();
                reqBuilder.url(url);
                reqBuilder.post(body);
                Request request = reqBuilder.build();
                Response response = client.newCall(request).execute();

                String res = response.body().string();

                JSONObject jObj = new JSONObject();
                jObj.put("statusCode", 1);
                jObj.put("response", res);
                return jObj.toString();

            } else if (reqMethod == RequestMethod.MULTIPART) {

                MediaType MEDIA_TYPE = fileName.endsWith("png") ?
                        MediaType.parse("image/png") : MediaType.parse("image/jpeg");

                MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
                multipartBuilder.setType(MultipartBody.FORM);

                multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(MEDIA_TYPE, file));

                RequestBody body = multipartBuilder.build();

                Request.Builder reqBuilder = new Request.Builder();
                reqBuilder.url(url);
                reqBuilder.post(body);
                Request request = reqBuilder.build();
                Response response = client.newCall(request).execute();
                String res = response.body().string();


                JSONObject jObj = new JSONObject();
                jObj.put("statusCode", 1);
                jObj.put("response", res);
                return jObj.toString();
            }

        } else {

            JSONObject jObj = new JSONObject();
            jObj.put("statusCode", 0);
            jObj.put("response", context.getString(R.string.no_internet));
            return jObj.toString();
        }
    } catch (final Exception e) {
        e.printStackTrace();
        JSONObject jObj = new JSONObject();
        try {
            jObj.put("statusCode", 0);
            jObj.put("response", e.toString());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return jObj.toString();
    }

    return null;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    try {
        JSONObject jObj = new JSONObject(result);
        if (jObj.getInt("statusCode") == 1) {
            listener.onSuccess(requestId, jObj.getString("response"));
        } else {
            listener.onError(requestId, jObj.getString("response"));
        }
    } catch (Exception e) {
        listener.onError(requestId, result);
    } finally {
        dismissProgressDialog();
    }
}


private void showProgressDialog() {
    progressDialog = new MyProgressDialog(context);
}

private void dismissProgressDialog() {
    if (progressDialog != null && progressDialog.isShowing()) {
        progressDialog.dismiss();
        progressDialog = null;
    }
}


private static NetworkManager instance = null;
private Set<RequestListener> arrRequestListeners = null;
private int requestId;
public boolean isProgressVisible = false;

private NetworkManager() {
    arrRequestListeners = new HashSet<>();
    arrRequestListeners = Collections.synchronizedSet(arrRequestListeners);
}

public static NetworkManager getInstance() {
    if (instance == null)
        instance = new NetworkManager();
    return instance;
}

public synchronized int addRequest(final HashMap<String, String> params, Context context, RequestMethod reqMethod, String apiMethod) {

    try {

        String url = Constants.WEBSERVICE_URL + apiMethod;
        requestId = UniqueNumberUtils.getInstance().getUniqueId();

        NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, reqMethod, isProgressVisible);
        networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    } catch (Exception e) {
        onError(requestId, e.toString() + e.getMessage());
    }

    return requestId;
}



public synchronized int addMultipartRequest(final HashMap<String,String> params, File file, String fileName, Context context, RequestMethod reqMethod, String apiMethod) {

    try {

        String url = Constants.WEBSERVICE_URL + apiMethod;
        requestId = UniqueNumberUtils.getInstance().getUniqueId();

        NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, file, fileName, reqMethod, isProgressVisible);
        networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    } catch (Exception e) {
        onError(requestId, e.toString() + e.getMessage());
    }

    return requestId;
}

public void isProgressBarVisible(boolean isProgressVisible) {
    this.isProgressVisible = isProgressVisible;
}

public void setListener(RequestListener listener) {
    try {
        if (listener != null && !arrRequestListeners.contains(listener)) {
            arrRequestListeners.add(listener);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void onSuccess(int id, String response) {

    if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
        for (RequestListener listener : arrRequestListeners) {
            if (listener != null)
                listener.onSuccess(id, response);
        }
    }
}

@Override
public void onError(int id, String message) {
    try {
        if (Looper.myLooper() == null) {
            Looper.prepare();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
        for (final RequestListener listener : arrRequestListeners) {
            if (listener != null) {
                listener.onError(id, message);
            }
        }
    }
}

public void removeListener(RequestListener listener) {
    try {
        arrRequestListeners.remove(listener);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

创建RequestListner intreface

public void onSuccess(int id, String response);

public void onError(int id, String message);

获得唯一编号

private static UniqueNumberUtils INSTANCE = new UniqueNumberUtils();

private AtomicInteger seq;

private UniqueNumberUtils() {
    seq = new AtomicInteger(0);
}

public int getUniqueId() {
    return seq.incrementAndGet();
}

public static UniqueNumberUtils getInstance() {
    return INSTANCE;
}


文章来源: Android GET and POST Request