2

谁能指出我发送 GET 和 POST 请求的方法的良好实现。他们有很多方法可以做到这一点,我正在寻找最好的实施方式。其次,是否有一种通用的方式来发送这两种方法,而不是使用两种不同的方式。毕竟 GET 方法仅在查询字符串中具有参数,而 POST 方法使用参数的标头。

谢谢。

4

6 回答 6

5

您可以使用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();

  }
}
于 2012-08-13T17:58:41.223 回答
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);
于 2012-08-13T17:53:19.793 回答
1

正如您所说:GET-Parameters 在 URL 中 - 因此您可以在 Webview 上使用 loadUrl() 来发送它们。

[..].loadUrl("http://www.example.com/data.php?param1=value1&param2=value2&...");
于 2012-08-13T17:40:31.720 回答
1

开发人员培训文档有一个关于 GET 请求的好例子。您负责将查询参数添加到 URL。

帖子是相似的,但正如你所说,完全不同。HttpConnectionURLConnection类可以同时做这两件事,而且很容易将帖子正文设置为输出流。

于 2012-08-13T17:52:30.153 回答
0
 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;
}
于 2017-03-09T08:01:52.903 回答
0
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 接口

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;
}
于 2017-06-05T07:02:58.643 回答