Android GET和POST请求

任何人都可以指出我很好地实现了发送GET和POST请求的方法。 他们有很多方法可以做到这些,我正在寻找最好的实施方案。 其次是有一种通用的方法来发送这两种方法,而不是使用两种不同的方式。 在所有GET方法仅在查询字符串中具有参数之后,而POST方法使用参数的标题。

谢谢。

您可以使用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请求看起来会有所不同,但大部分代码都是一样的。 您不必担心使用流输出或指定content-length或content-type:

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

我更喜欢使用专用类来执行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 fetchData(Info info) throws JSONException, IOException { List out = new LinkedList(); 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 nameValuePairs = new ArrayList(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); 

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

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

开发人员培训文档就GET请求提供了一个很好的示例 。 您负责将查询参数添加到URL。

邮政是相似的,但正如你所说,完全不同。 HttpConnectionURLConnection类可以同时执行这两个操作,只需使用输出流设置post body即可。

  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; } 
 private RequestListener listener; private int requestId; private HashMap 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 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 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 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 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 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; }