Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android获取和发布请求_Java_Android_Post_Get - Fatal编程技术网

Java Android获取和发布请求

Java Android获取和发布请求,java,android,post,get,Java,Android,Post,Get,谁能告诉我一个发送GET和POST请求的好方法。他们有很多方法来实现这些,我正在寻找最好的实现。其次,是否有一种通用的方法来发送这两种方法,而不是使用两种不同的方法。毕竟,GET方法在查询字符串中只包含参数,而POST方法使用参数的头 谢谢。正如您所说:GET参数在URL中-因此您可以在Webview上使用loadUrl()发送它们 [..].loadUrl("http://www.example.com/data.php?param1=value1&param2=value2&

谁能告诉我一个发送GET和POST请求的好方法。他们有很多方法来实现这些,我正在寻找最好的实现。其次,是否有一种通用的方法来发送这两种方法,而不是使用两种不同的方法。毕竟,GET方法在查询字符串中只包含参数,而POST方法使用参数的头


谢谢。

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

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

开发人员培训文档有一个。您负责将查询参数添加到URL


这篇文章很相似,但正如你所说,完全不同。该类可以同时完成这两项工作,只需使用输出流设置post正文就很容易了。

我更喜欢使用专用类来完成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);
    }
}

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

  }
}
获取唯一编号

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

你在哪里指定URL。execute方法接受HTTP URI请求。我如何使用URL创建它。其次,为什么execute方法是公共的?您不再需要导入了。
setMethod
现在是
setRequestMethod
 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<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();
    }
}
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;
}