How to call http request in android (安卓网络请求写法)

本文详细介绍了在Android应用中执行HTTP请求的多种方法,包括GET和POST请求的实现,特别强调了通过创建可复用的类来简化代码维护。文章还提供了如何构建请求头和处理响应的具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Normally, there are many approaches to call http request in Andriod. Here I only explain following methods to call http request:

Hopefully, it helps android developer

in my opition, it should be utilize class in your project so that you can call this class everywhere. you only need to maintain one piece of source code. No necessary to reimplement your own source code again.

package rib.com.example.Util;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.io.IOUtils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import rib.com.mctwo.Bean.LoginClientContext;

/**
 * Http请求工具类
 *
 * @author Tony Peng
 * @version v1.0.1
 * @since 2018-12-25
 */
public class HttpRequestUtil {
  

    private static final String AUTHORIZATION = "Authorization";
    private static final String BEARER = "Bearer ";
    private static final String CLIENTCONTEXT = "Client-Context";

    /*
    *
    * Get as json request
    * */
    public static String getAsJson(String url, Map<String, String> headers, String param)
    {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            
            URLConnection connection = realUrl.openConnection();


            // 设置通用的请求属性
            // initialize headers
            Iterator<Map.Entry<String, String>> entries = headers.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, String> entry = entries.next();
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }

            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

  

    /*
     * Generate Header via token and client context
     * @author Tony Peng
     * */
    public static Map<String, String> generateHeaders(String token, Object clientContext ) {

        Map<String, String> header = new HashMap<String, String>();

        // add token first
        if(token != null){
            token = token.replaceAll("\"","");
            token = token.trim();
            header.put(AUTHORIZATION, BEARER + token);
        }

        // add client context string
        if (clientContext != null) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                String jsonData = mapper.writeValueAsString(clientContext);

                if (jsonData != null) {
                    header.put(CLIENTCONTEXT, jsonData);
                }
            } catch (Exception e) {

            }
        } else {
            LoginClientContext cc = new LoginClientContext();
            cc.setClientId(0);
            cc.setCompanyCode("");
            cc.setSignedInClientId(0);
            cc.setPermissionClientId(0);
            cc.setPermissionRoleId(0);
            cc.setDataLanguageId(1);
            cc.setCulture("en-us");
            cc.setLanguage("en");

            try {
                ObjectMapper mapper = new ObjectMapper();
                String jsonData = mapper.writeValueAsString(cc);

                if (jsonData != null) {
                    header.put(CLIENTCONTEXT, jsonData);
                }
            } catch (Exception e) {

            }
        }

        header.put("Content-Type", "application/json");
        header.put("charset", "utf-8");
        header.put("User-Agent","Mozilla/5.0 ( compatible ) ");
        header.put("Accept", "*/*");

        return header;
    }

    /**
     * 发送post请求
     *
     * @param requestUrl
     *            请求地址
     * @param headers
     *            请求头
     * @param params
     *            参数
     * @return 返回结果
     * @throws IOException
     */
    public static String sendPost( String requestUrl, Map<String, String> headers, String params
                                  ) throws IOException {

        byte[] requestBytes = params.getBytes("utf-8"); // 将参数转为二进制流
        HttpClient httpClient = new HttpClient();// 客户端实例化
        PostMethod postMethod = new PostMethod(requestUrl);

        // 设置请求头
        // initialize headers
        Iterator<Map.Entry<String, String>> entries = headers.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = entries.next();
            postMethod.setRequestHeader(entry.getKey(), entry.getValue());
        }

        postMethod.setRequestHeader("Content-Type", "application/json");
        InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
                requestBytes.length);
        RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
                requestBytes.length, "application/json; charset=utf-8"); // 请求体
        postMethod.setRequestEntity(requestEntity);
        httpClient.executeMethod(postMethod);// 执行请求
        InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流

        String result = IOUtils.toString(soapResponseStream);;// 从输入流中读取数据
        return result;
    }

}


 Normally, you had better saperete your request header. Here, I am using method "generateHeaders" to assembly your request headers. For individual developer, you just need to build your own header and sort out related URL, you can call it properly.

Note that, you had better add following packages lest that you will have complier errors (build gradle - app

implementation 'org.apache.servicemix.bundles:org.apache.servicemix.bundles.commons-httpclient:3.1_7'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.9.8'
implementation 'org.kie.modules:org-apache-commons-io-main:6.5.0.Final'

 

package com.zhy.http.okhttp; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.util.Log; import com.zhy.http.okhttp.cookie.SimpleCookieJar; import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Response; import com.zhy.http.okhttp.builder.GetBuilder; import com.zhy.http.okhttp.builder.PostFileBuilder; import com.zhy.http.okhttp.builder.PostFormBuilder; import com.zhy.http.okhttp.builder.PostStringBuilder; import com.zhy.http.okhttp.callback.Callback; import com.zhy.http.okhttp.https.HttpsUtils; import com.zhy.http.okhttp.request.RequestCall; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; /** * Created by zhy on 15/8/17. */ public class OkHttpUtils { public static final String TAG = "OkHttpUtils"; public static final long DEFAULT_MILLISECONDS = 10000; private static OkHttpUtils mInstance; private OkHttpClient mOkHttpClient; private Handler mDelivery; private OkHttpUtils() { OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder(); //cookie enabled okHttpClientBuilder.cookieJar(new SimpleCookieJar()); mDelivery = new Handler(Looper.getMainLooper()); if (true) { okHttpClientBuilder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } mOkHttpClient = okHttpClientBuilder.build(); } private boolean debug; private String tag; public OkHttpUtils debug(String tag) { debug = true; this.tag = tag; return this; } public static OkHttpUtils getInstance() { if (mInstance == null) { synchronized (OkHttpUtils.class) { if (mInstance == null) { mInstance = new OkHttpUtils(); } } } return mInstance; } public Handler getDelivery() { return mDelivery; } public OkHttpClient getOkHttpClient() { return mOkHttpClient; } public static GetBuilder get() { return new GetBuilder(); } public static PostStringBuilder postString() { return new PostStringBuilder(); } public static PostFileBuilder postFile() { return new PostFileBuilder(); } public static PostFormBuilder post() { return new PostFormBuilder(); } public void execute(final RequestCall requestCall, Callback callback) { if (debug) { if(TextUtils.isEmpty(tag)) { tag = TAG; } Log.d(tag, "{method:" + requestCall.getRequest().method() + ", detail:" + requestCall.getOkHttpRequest().toString() + "}"); } if (callback == null) callback = Callback.CALLBACK_DEFAULT; final Callback finalCallback = callback; requestCall.getCall().enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, final IOException e) { sendFailResultCallback(call, e, finalCallback); } @Override public void onResponse(final Call call, final Response response) { if (response.code() >= 400 && response.code() <= 599) { try { sendFailResultCallback(call, new RuntimeException(response.body().string()), finalCallback); } catch (IOException e) { e.printStackTrace(); } return; } try { Object o = finalCallback.parseNetworkResponse(response); sendSuccessResultCallback(o, finalCallback); } catch (Exception e) { sendFailResultCallback(call, e, finalCallback); } } }); } public void sendFailResultCallback(final Call call, final Exception e, final Callback callback) { if (callback == null) return; mDelivery.post(new Runnable() { @Override public void run() { callback.onError(call, e); callback.onAfter(); } }); } public void sendSuccessResultCallback(final Object object, final Callback callback) { if (callback == null) return; mDelivery.post(new Runnable() { @Override public void run() { callback.onResponse(object); callback.onAfter(); } }); } public void cancelTag(Object tag) { for (Call call : mOkHttpClient.dispatcher().queuedCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } for (Call call : mOkHttpClient.dispatcher().runningCalls()) { if (tag.equals(call.request().tag())) { call.cancel(); } } } public void setCertificates(InputStream... certificates) { mOkHttpClient = getOkHttpClient().newBuilder() .sslSocketFactory(HttpsUtils.getSslSocketFactory(certificates, null, null)) .build(); } public void setConnectTimeout(int timeout, TimeUnit units) { mOkHttpClient = getOkHttpClient().newBuilder() .connectTimeout(timeout, units) .build(); } }
In Android development, encapsulating a website typically refers to creating an interface that allows you to interact with the website's content without exposing its underlying implementation details or hosting the entire site within your app. This is often done using webviews and APIs. Here's a basic explanation: 1. **WebView**: WebView is a built-in component that lets you display HTML, CSS, and JavaScript content inside an Android app. You can load websites by setting the WebView's `loadUrl()` method with the desired URL. ```java WebView webView = findViewById(R.id.web_view); webView.loadUrl("https://example.com"); ``` 2. **Content Providers (optional)**: If you need to access specific data from the website, you might consider using a Content Provider to fetch that information. For instance, if the website offers JSON data, you can create a custom content provider for your app to consume. 3. **API Integration**: If the website has an API, use Android's HTTP clients like `HttpClient` or later `OkHttp`, or even better, with Retrofit for a more structured approach. This allows you to make calls to the server programmatically. 4. **Separation of Concerns**: To maintain encapsulation, separate the code responsible for interacting with the website (the "adapter" layer) from your app's core logic. This helps keep your app clean and maintainable. ```java // Using Retrofit for API integration Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); ApiService service = retrofit.create(ApiService.class); Call<ApiResponse> call = service.getData(); call.enqueue(new Callback<ApiResponse>() { @Override public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) { // Handle API response } @Override public void onFailure(Call<ApiResponse> call, Throwable t) { // Handle errors } }); ``` **
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值