草庐IT

java - 如何将 HttpUrlConnection 的逻辑拆分为多个方法?

coder 2023-12-15 原文

我有多个 Activity ,每个 Activity 都从不同的 URL 和不同的 HTTP 方法(如 POSTGETPUTDELETE等 有些请求有头数据,有些有正文,有些可能两者都有。 我正在使用具有多个构造函数的单个 AsyncTask 类来传递来自 Activity 的数据,以便我可以将它们添加到 HttpUrlConnection 实例。

我试过这个教程:http://cyriltata.blogspot.in/2013/10/android-re-using-asynctask-class-across.html .

但是上面的教程使用了HttpClientNameValuePair。我将 NameValuePair 替换为 Pair。但我发现很难使用 HttpUrlConnection 实现相同的逻辑,因为我需要向我的请求添加多个 POST 数据和 header 。

但是返回的字符串是空的。我该如何正确实现这种情况?

完整代码:

public class APIAccessTask extends AsyncTask<String,Void,String> {
URL requestUrl;
Context context;
HttpURLConnection urlConnection;
List<Pair<String,String>> postData, headerData;
String method;
int responseCode = HttpURLConnection.HTTP_NOT_FOUND;


APIAccessTask(Context context, String requestUrl, String method){
    this.context = context;
    this.method = method;
    try {
        this.requestUrl = new URL(requestUrl);
    }
    catch(Exception ex){
        ex.printStackTrace();
    }
 }


APIAccessTask(Context context, String requestUrl, String method,    List<Pair<String,String>> postData,){
    this(context, requestUrl, method);
    this.postData = postData;
}

APIAccessTask(Context context, String requestUrl, String method, List<Pair<String,String>> postData,
              List<Pair<String,String>> headerData){
    this(context, requestUrl,method,postData);
    this.headerData = headerData;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {

    setupConnection();

    if(method.equals("POST"))
    {
        return httpPost();
    }

    if(method.equals("GET"))
    {
        return httpGet();
    }

    if(method.equals("PUT"))
    {
        return httpPut();
    }

    if(method.equals("DELETE"))
    {
        return httpDelete();
    }
    if(method.equals("PATCH"))
    {
        return httpPatch();
    }

    return null;
}

@Override
protected void onPostExecute(String result) {
    Toast.makeText(context,result,Toast.LENGTH_LONG).show();
    super.onPostExecute(result);
}

void setupConnection(){
    try {
        urlConnection = (HttpURLConnection) requestUrl.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setChunkedStreamingMode(0);
        if(headerData != null){
            for (Pair pair: headerData)
            {
                urlConnection.setRequestProperty(pair.first.toString(), Base64.encodeToString(pair.second.toString().getBytes(),Base64.DEFAULT));
            }
        }
    }
    catch(Exception ex) {
        ex.printStackTrace();
    }

}

private String httpPost(){
    try{
        urlConnection.setRequestMethod("POST");
    }
    catch (Exception ex){
        ex.printStackTrace();

    return stringifyResponse();
}

String httpGet(){

    try{
        urlConnection.setRequestMethod("GET");
    }
    catch (Exception ex){
        ex.printStackTrace();
    }
    return stringifyResponse();
}

String httpPut(){

    try{
        urlConnection.setRequestMethod("PUT");
    }
    catch (Exception ex){
        ex.printStackTrace();
    }
    return stringifyResponse();
}

String httpDelete(){
    try{
        urlConnection.setRequestMethod("DELETE");
    }
    catch (Exception ex){
        ex.printStackTrace();
    }
    return stringifyResponse();

}

String httpPatch(){
    try{
        urlConnection.setRequestMethod("PATCH");
    }
    catch (Exception ex){
        ex.printStackTrace();
    }
    return stringifyResponse();

}

String stringifyResponse() {

    StringBuilder sb = new StringBuilder();
    try {
        OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
        writer.write(getQuery(postData));
        writer.flush();
        writer.close();
        out.close();

        urlConnection.connect();
        responseCode = urlConnection.getResponseCode();
        if (responseCode == 200) {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return sb.toString();
}


private String getQuery(List<Pair<String,String>> params) throws UnsupportedEncodingException{
    Uri.Builder builder = null;
    for (Pair pair : params)
    {
         builder = new Uri.Builder()
                .appendQueryParameter(pair.first.toString(), pair.second.toString());
                }
    return builder.build().getEncodedQuery();
}
}

最佳答案

IMO,你可以引用我下面的示例代码:

   /**         
     * HTTP request using HttpURLConnection
     *
     * @param method
     * @param address
     * @param header
     * @param mimeType
     * @param requestBody
     * @return
     * @throws Exception
     */
    public static URLConnection makeURLConnection(String method, String address, String header, String mimeType, String requestBody) throws Exception {
        URL url = new URL(address);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(!method.equals(HTTP_METHOD_GET));
        urlConnection.setRequestMethod(method);

        if (isValid(header)) {   // let's assume only one header here             
            urlConnection.setRequestProperty(KEYWORD_HEADER_1, header);
        }

        if (isValid(requestBody) && isValid(mimeType) && !method.equals(HTTP_METHOD_GET)) {
            urlConnection.setRequestProperty(KEYWORD_CONTENT_TYPE, mimeType);
            OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8");
            writer.write(requestBody);
            writer.flush();
            writer.close();
            outputStream.close();
        }

        urlConnection.connect();

        return urlConnection;
    }

requestBody 是使用以下方法生成的:

    public static String buildRequestBody(Object content) {
        String output = null;
        if ((content instanceof String) ||
                (content instanceof JSONObject) ||
                (content instanceof JSONArray)) {
            output = content.toString();
        } else if (content instanceof Map) {
            Uri.Builder builder = new Uri.Builder();
            HashMap hashMap = (HashMap) content;
            if (isValid(hashMap)) {
                Iterator entries = hashMap.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
                    entries.remove(); // avoids a ConcurrentModificationException
                }
                output = builder.build().getEncodedQuery();
            }
        } else if (content instanceof byte[]) {
            try {
                output = new String((byte[]) content, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        return output;
    }
}

然后,在您的 AsyncTask 类中,您可以调用:

       String url = "http://.......";
       HttpURLConnection urlConnection;
       Map<String, String> stringMap = new HashMap<>();           
       stringMap.put(KEYWORD_USERNAME, "bnk");
       stringMap.put(KEYWORD_PASSWORD, "bnk123");
       String requestBody = buildRequestBody(stringMap);
       try {
           urlConnection = (HttpURLConnection) Utils.makeURLConnection(HTTP_METHOD_POST, url, null, MIME_FORM_URLENCODED, requestBody);               
           if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
               // do something...
           } else {
               // do something...
           }
           ...
       } catch (Exception e) {
           e.printStackTrace();
       }

       String url = "http://.......";
       HttpURLConnection urlConnection;
       JSONObject jsonBody;                      
       String requestBody;
       try {
           jsonBody = new JSONObject();
           jsonBody.put("Title", "Android Demo");
           jsonBody.put("Author", "BNK");
           requestBody = Utils.buildRequestBody(jsonBody);
           urlConnection = (HttpURLConnection) Utils.makeURLConnection(HTTP_METHOD_POST, url, null, MIME_JSON, requestBody);               
           if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
               // do something...
           } else {
               // do something...
           }
           ...
       } catch (Exception e) {
           e.printStackTrace();
       }

关于java - 如何将 HttpUrlConnection 的逻辑拆分为多个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34408126/

有关java - 如何将 HttpUrlConnection 的逻辑拆分为多个方法?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  6. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  7. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  8. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  9. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  10. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

随机推荐