Android中的HTTP Patch请求

16

我正在尝试从一个安卓应用程序中进行HTTP Patch请求,但一直没能弄清楚。看起来HTTPUrlConnection不支持PATCH。在Android中包含的库中似乎没有HttpPatch(链接)。有什么主意吗?

4个回答

20

如果绝对需要使用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;
    }

}

更好的选择是包含可以从这里下载的jar http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.2.1 如果您只添加上面的类,您也会遇到“NotThreadSafe”解决问题。 - iutinvg
@Slava 这就是我所说的 "... 你需要将 Apache HttpClient 作为 jar 依赖项导入"。你也可以直接从他们的网站下载该 jar 包。 - mercutio
只是出于好奇,你不会这样做吗(URL.create(uri));?还是这只是我个人的习惯? - WORMSS
@WORMSS 两种方式都可以,但这种方式可以更好地控制你的构造函数。 - mercutio
如何使用HTTP的patch方法发送图像? - Anand Savjani
显示剩余2条评论

14

我们创建了自己的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;
    }
}

4

看起来OkHttp支持patch请求

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

2

这太神奇了。它的工作效果非常好。

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

1
对于“work”的某些值,它仍然不是一个PATCH请求。 - Julian Reschke
1
因为你正在与的服务器“理解”Method-Override头字段。但它在传输中仍然不是PATCH请求。 - Julian Reschke
即使是临时解决方案,它对我来说也是最快的。谢谢。 - Gulshan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接