2012-08-13 278 views
1

任何人都可以指出我發送GET和POST請求的方法的良好實現。他們有很多方法來做到這一點,我正在尋找最好的實施。其次是有一種通用的方式來發送這兩種方法,而不是使用兩種不同的方式。所有GET方法僅在查詢字符串中具有參數,而POST方法使用Params的標題。Android GET和POST請求

謝謝。

回答

3

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

    } 
} 
1

正如你所說:GET參數在URL中 - 所以你可以在你的Webview上使用loadUrl()來發送它們。

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

我更喜歡使用專用類來執行GET/POST和任何HTTP連接或請求。 此外我使用HttpClient來執行這些GET/POST方法。

以下是我的項目示例。我需要線程安全執行,所以有ThreadSafeClientConnManager

存在使用GET(fetchData)和POST(sendOrder)

正如你可以看到execute是用於執行HttpUriRequest一般方法的一個例子 - 也可以是POST或GET。因爲有時我使用自定義(或動態)GET/POST請求

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

EDIT

execute方法是公開的。

如果你有URL對象可以傳遞給execute方法:

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

你在哪裏指定URL。 execute方法採用HTTP URI請求。我如何使用URL創建這個。第二,爲什麼執行方法是公開的? – AndroidDev 2012-08-13 18:48:01

+0

@ user365019剛編輯答案 – Xeon 2012-08-13 19:13:55

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

intreface

public void onSuccess(int id, String response); 

public void onError(int id, String message); 

創建RequestListner獲得唯一編號

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