【问题标题】:HTTP Patch request from Android来自 Android 的 HTTP 补丁请求
【发布时间】:2015-07-17 19:35:32
【问题描述】:

我正在尝试从 Android 应用程序发出 HTTP Patch 请求,但无法弄清楚。 HTTPUrlConnection 似乎不支持 PATCH。 HttpPatch 似乎不在 Android (link) 上包含的库中。有什么想法吗?

【问题讨论】:

    标签: android http


    【解决方案1】:

    如果绝对需要 Patch 方法,则必须将 Apache HttpClient 作为 jar 依赖项导入。这将在一定程度上增加您的应用程序的大小,但这应该不是一个大问题。

    作为一种解决方法,您可以尝试在您的应用中仅包含此 java 代码:

    /*
     * ====================================================================
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor license agreements.  See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership.  The ASF licenses this file
     * to you under the Apache License, Version 2.0 (the
     * "License"); you may not use this file except in compliance
     * with the License.  You may obtain a copy of the License at
     *
     *   http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing,
     * software distributed under the License is distributed on an
     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     * KIND, either express or implied.  See the License for the
     * specific language governing permissions and limitations
     * under the License.
     * ====================================================================
     *
     * This software consists of voluntary contributions made by many
     * individuals on behalf of the Apache Software Foundation.  For more
     * information on the Apache Software Foundation, please see
     * <http://www.apache.org/>.
     *
     */
    
    package org.apache.http.client.methods;
    
    import java.net.URI;
    
    import org.apache.http.annotation.NotThreadSafe;
    
    /**
     * HTTP PATCH method.
     * <p>
     * The HTTP PATCH method is defined in <a
     * href="http://tools.ietf.org/html/rfc5789">RF5789</a>: <blockquote> The PATCH
     * method requests that a set of changes described in the request entity be
     * applied to the resource identified by the Request- URI. Differs from the PUT
     * method in the way the server processes the enclosed entity to modify the
     * resource identified by the Request-URI. In a PUT request, the enclosed entity
     * origin server, and the client is requesting that the stored version be
     * replaced. With PATCH, however, the enclosed entity contains a set of
     * instructions describing how a resource currently residing on the origin
     * server should be modified to produce a new version. </blockquote>
     * </p>
     *
     * @since 4.2
     */
    @NotThreadSafe
    public class HttpPatch extends HttpEntityEnclosingRequestBase {
    
        public final static String METHOD_NAME = "PATCH";
    
        public HttpPatch() {
            super();
        }
    
        public HttpPatch(final URI uri) {
            super();
            setURI(uri);
        }
    
        public HttpPatch(final String uri) {
            super();
            setURI(URI.create(uri));
        }
    
        @Override
        public String getMethod() {
            return METHOD_NAME;
        }
    
    }
    

    【讨论】:

    • 我早该想到的。非常感谢。将 HttpPatch 添加到我的项目后,我就可以让它工作了。
    • 更好的选择是包含可以从这里下载的 jar mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/… 如果你只是在上面添加类你也会遇到NotThreadSafe 分辨率的问题。
    • @Slava 这就是我所说的“......您必须将 Apache HttpClient 作为 jar 依赖项导入”。您也可以直接从他们的网站下载 jar。
    • 只是出于好奇,你会不会这样做(URL.create(uri)); ?或者这只是我做的事情?
    • @WORMSS 这两种方式都很好,但这样你可以更好地控制你的构造函数。
    【解决方案2】:

    我们创建了自己的 HttpPatch 类,例如:

    public class HttpPatch extends HttpPost {
        public static final String METHOD_PATCH = "PATCH";
    
        public HttpPatch(final String url) {
            super(url);
        }
    
        @Override
        public String getMethod() {
            return METHOD_PATCH;
        }
    }
    

    【讨论】:

      【解决方案3】:

      OkHttp 好像支持补丁

      Request request = Request.Builder().url().patch().build();
      

      【讨论】:

        【解决方案4】:

        它太棒了。它的作用就像一个魅力。

        使用 HttpPost 调用并将标头设置为

        httpost.setHeader("X-HTTP-Method-Override", "PATCH");

        或者

        只需复制并粘贴此代码

        public static JSONObject makeRequestCheck(String hostname, String token,String proId,String taskGrpId, String taskId) throws Exception {
        
            SSLSocketFactory sslFactory = new SimpleSSLSocketFactory(null);
            sslFactory
                    .setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory
                    .getSocketFactory(), 80));
            registry.register(new Scheme("https", sslFactory, 443));
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params,
                    registry);
            HttpClient client = new DefaultHttpClient(ccm, params);
            String hostnamee = hostname+"projects/"+proId+"/taskgroups/"+taskGrpId+"/tasks/"+taskId+"/complete";
            HttpPost httpost = new HttpPost(hostnamee);
            System.out.println(hostnamee);
        //  StringEntity se = new StringEntity(jsonSignin.toString());
        
            HttpResponse response = null;
            try {
            //  httpost.setEntity(se);
                httpost.setHeader("X-HTTP-Method-Override", "PATCH");
                httpost.setHeader("Content-type", "application/json");
                httpost.setHeader("Accept", "*/*");
                httpost.setHeader("Accept-Encoding", "gzip, deflate");
                httpost.addHeader("Connection", "keep-alive");
                httpost.addHeader("Accept-Language", "en-GB,en-US;q=0.8,en;q=0.6");
                httpost.setHeader("User-Agent", "nnst");
                httpost.setHeader("Accept-Charset", "utf-8");
                if (token == "NV") {
                } else {
                    httpost.setHeader("Authorization", "Token" + " " + token);
                }
                response = client.execute(httpost);
        
            } catch (Exception e) {
                System.out.println("::my Exception ::" + e);
            }
            if (response == null) {
                System.out.println("no data");
            }
            String output = EntityUtils.toString(response.getEntity());
        
            JSONObject jobj = new JSONObject(output);
        
            return jobj;
        }
        

        【讨论】:

        • 对于“工作”的某些价值。这仍然不是 PATCH 请求。
        • 因为您正在与之交谈的服务器“理解” Method-Override 标头字段。它仍然不是在线上的 PATCH 请求。
        • 即使是临时解决方案,它对我来说也是最快的。谢谢。
        猜你喜欢
        • 2014-04-20
        • 2013-11-16
        • 1970-01-01
        • 2015-09-15
        • 1970-01-01
        • 2019-03-11
        • 2020-05-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多