HttpClient GET POST DELETE方法使用

package com.xiaobudian.childarticle.util;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.IOException;
import java.util.*;

/**
 * Created by hackcoder on 15-4-20.
 */
public class NetUtil {
    public static String GET(String url){
        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();

        // Create a method instance.
        GetMethod method = new GetMethod(url);

        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                return "Method failed: " + method.getStatusLine();
            }

            // Read the response body.
            byte[] responseBody = method.getResponseBody();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            return new String(responseBody);

        } catch (HttpException e) {
            System.err.println("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // Release the connection.
            method.releaseConnection();
        }
        return null;
    }
    public static String POST(String url,Map<String,Object> dataForm){
        HttpClient httpClient = new HttpClient();
        PostMethod post = new PostMethod(url);
        List<NameValuePair> data = new ArrayList<NameValuePair>();
        if(dataForm!=null){
            Set<String> keys = dataForm.keySet();
            for(String key:keys){
                NameValuePair nameValuePair = new NameValuePair(key, (String) dataForm.get(key));
                data.add(nameValuePair);
            }
        }
        post.setRequestBody(data.toArray(new NameValuePair[0]));
        try {
            int statusCode = httpClient.executeMethod(post);
            if (statusCode != HttpStatus.SC_OK) {
                return "Method failed: " + post.getStatusLine();
            }

            // Read the response body.
            byte[] responseBody = post.getResponseBody();
            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            return new String(responseBody);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            post.releaseConnection();
        }
        return null;
    }

    public static String DELETE(String url,Map<String,Object> dataForm){
        HttpClient httpClient = new HttpClient();
        DeleteMethod deleteMethod = new DeleteMethod(url);

        List<NameValuePair> data = new ArrayList<NameValuePair>();
        if(dataForm!=null){
            Set<String> keys = dataForm.keySet();
            for(String key:keys){
                NameValuePair nameValuePair = new NameValuePair(key, (String) dataForm.get(key));
                data.add(nameValuePair);
            }
        }
        deleteMethod.setQueryString(data.toArray(new NameValuePair[0]));
        try {
            int statusCode = httpClient.executeMethod(deleteMethod);
            if (statusCode != HttpStatus.SC_OK) {
                return "Method failed: " + deleteMethod.getStatusLine();
            }

            // Read the response body.
            byte[] responseBody = deleteMethod.getResponseBody();
            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            return new String(responseBody);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            deleteMethod.releaseConnection();
        }
        return null;
    }

}

时间: 2024-08-19 06:23:32

HttpClient GET POST DELETE方法使用的相关文章

[原创]java WEB学习笔记79:Hibernate学习之路--- 四种对象的状态,session核心方法:save()方法,persist()方法,get() 和 load() 方法,update()方法,saveOrUpdate() 方法,merge() 方法,delete() 方法,evict(),hibernate 调用存储过程,hibernate 与 触发器协同工作

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱好者,互联网技术发烧友 微博:伊直都在0221 QQ:951226918 -----------------------------------------------------------------------------------------------------------------

java的File类的 delete方法删不掉文件的原因分析

先举几个可以删除掉文件和删除不掉文件的例子(先在F盘创建test1.txt文件,然后可以直接拷贝代码到IDE执行),最后总结下原因: 例子一:下面的例子毫无疑问是能够删除掉文件的 import java.io.File; import java.io.IOException; public class Test { public static void main(String[] args) throws IOException { File file = new File("F:/test1.

ASP.NET MVC 5 - 查询Details和Delete方法

原文:ASP.NET MVC 5 - 查询Details和Delete方法 在这部分教程中,接下来我们将讨论自动生成的Details和Delete方法. 查询Details和Delete方法 打开Movie控制器并查看Details方法. public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Movie movie

对 File.Delete 方法的一点看法

在我写的"推箱子"程序的 DataFile 类中有下面这么一个方法: /// <summary> ///  删除通关步骤文件 /// </summary> /// <param name="level">关数</param> private void DeleteStepsFile(int level) { File.Delete(GetStepsFileName(fileName, level)); } 该方法主要用

学习ASP .NET MVC5官方教程总结(十一)Details 和 Delete 方法详解

学习ASP .NET MVC5官方教程总结(十一)Details 和 Delete 方法详解 在这一章,我们将研究一下自动生成的 Details 和Delete 方法. 打开Movie控制器,找到Details方法. // // GET: /Movies/Details/5 public ActionResult Details(Int32 id) { Movie movie = db.Movies.Find(id); if (movie == null) { return HttpNotFou

httpclient 4.3 psot方法上传文件与参数 中文乱码解决

废话不多说,直接上有码的! 1 package httpclient; 2 3 import java.io.File; 4 import java.nio.charset.Charset; 5 6 import org.apache.http.Consts; 7 import org.apache.http.Header; 8 import org.apache.http.HttpEntity; 9 import org.apache.http.client.methods.Closeable

javascript delete方法

学习delete可以参考下面两个博客,写的都很好,本文大部分参考与以下两个博客 http://www.cnblogs.com/windows7/archive/2010/03/28/1698387.html http://my.oschina.net/warmcafe/blog/75845 一.javascript delete的作用 delete方法用于删除对象的指定元素(包括变量和函数) 1.新建一个变量flower,并新添一个属性变量name,然后delete该属性 var flower=

[转]ASP.NET MVC 5 - 查询Details和Delete方法

在这部分教程中,接下来我们将讨论自动生成的Details和Delete方法. 查询Details和Delete方法 打开Movie控制器并查看Details方法. public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Movie movie = db.Movies.Find(id); if (movie == nu

http delete 方法传参数遇到java.net.ProtocolException: DELETE does not support writing的问题

最近在测试通过http delete method传参数调用服务端方法,遇到了java.net.ProtocolException: DELETE does not support writing try { url = new URL(path); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestMethod(me