`
冰糖葫芦有点酸
  • 浏览: 29515 次
  • 性别: Icon_minigender_2
  • 来自: 武汉
社区版块
存档分类
最新评论

HttpClient Send GET/POST Request

    博客分类:
  • Java
 
阅读更多
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

/**
 * Send Get Request
 */
public void getRequest(String url) {

    HttpClient client = new HttpClient();
    GetMethod getMethod = new GetMethod(url);

    try {

        int statusCode = client.executeMethod(getMethod);

        if (statusCode == HttpStatus.SC_OK) {
            //TODO
        } else {
            throw new Exception("Failed to get: " + getMethod.getResponseBodyAsString());
        }

    } catch (Exception e) {
        logger.error(e);
    } finally {
        //release connection
        getMethod.releaseConnection();
    }
}

/**
 * Send Post Request with JSON
 * @return JSON from Response
 */
private JsonObject postRequest(String url, JsonObject requestBody) {
    JsonObject responseJsonObj = null;

    HttpClient httpClient = new HttpClient();
    PostMethod postRequest = new PostMethod(url);

    try {
        StringRequestEntity requestEntity = new StringRequestEntity(jsonString, "application/json", "UTF-8");
        //set request body
        postRequest.setRequestEntity(requestEntity);
        //set request header
        postRequest.addRequestHeader("Content-Type", "application/json");
        postRequest.addRequestHeader("Accept", "application/json");
        //execute post request
        httpClient.executeMethod(postRequest);

        int statusCode = postRequest.getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            String postResponse = postRequest.getResponseBodyAsString();
            JsonParser parser = new JsonParser();
            responseJsonObj = (JsonObject) parser.parse(postResponse);
        } else {
            throw new Exception("Failed to post data: " + postRequest.getResponseBodyAsString());
        }

    }catch (Exception ex) {
        logger.error(ex);
    } finally {
        //release connection
        postRequest.releaseConnection();
    }
    return responseJsonObj;
}

Note:
1. Here need to depend on "commons-httpclient.jar"
2. For post request, if request header not be set, may throw "General Error: Request method 'POST' not supported "
分享到:
评论

相关推荐

    java HttpClient 发送GET请求和带有表单参数的POST请求教程例子

    public static String sendPostRequest(String requestUrl) { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(requestUrl); List<NameValuePair> params = new ArrayList...

    Android-HttpClient工具类简单轻松的实现getpostput和delete请求

    public static String sendPostRequest(String url, List<NameValuePair> params) throws IOException { HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); ...

    http发送Get和Post请求工具类

    在`HttpUtils`中,通常会包含两个主要方法:`sendGetRequest`和`sendPostRequest`,分别用于执行GET和POST请求。 1. **GET请求**: - GET请求常用于获取服务器上的资源,它是无状态的,参数通过URL传递。`...

    java 实现get,post请求

    以上代码中,`sendGetRequest`和`sendPostRequest`分别演示了GET和POST请求的发送。在实际应用中,可能需要根据实际需求添加错误处理和更复杂的参数设置。 总结,Java实现HTTP的GET和POST请求主要依赖于`...

    Android Get和Post方式访问网络

    private String sendPostRequest(String urlStr, String postData) { // 实现POST请求逻辑 } } ``` 在实际开发中,还需要注意网络权限的申请,如在AndroidManifest.xml中添加`...

    httpclient简单使用

    public String sendPostRequest(String url, String requestBody) throws IOException { // 发送POST请求并返回响应体 } } ``` 8. **异常处理和资源关闭** 执行HTTP请求时可能出现IOException,因此应妥善...

    HttpClient

    - 包含静态方法,如`sendGetRequest(String url, ResponseHandler<T> handler)`和`sendPostRequest(String url, String requestBody, ResponseHandler<T> handler)`,其中`ResponseHandler`用于处理响应内容。...

    httpClient例子

    通常,这个工具类会包含静态方法,如`sendGetRequest`和`sendPostRequest`,接受URL和其他必要参数,然后处理整个请求过程。 最后,压缩包中的`httpClientDemo`可能是包含这些示例代码的Java项目,导入到你的IDE后...

    【最新】C++ 使用libEvent实现http的post, get功能

    例如,你可以创建一个`HttpClient`类,包含`sendGet`和`sendPost`方法,以及必要的成员变量来存储HTTP客户端句柄和基础事件结构体。 文件名`console2`可能表示这是一个与控制台交互相关的示例代码,可能包含了如何...

    httpclient 工具类

    public static String sendPostRequest(String url, String param) throws IOException { HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new StringEntity(param, "UTF-8")); httpPost.setHeader...

    JAVA发送HttpClient请求及接收请求完整代码实例

    public static String sendPostRequest(String url, Map, String> params) { // 实现POST请求逻辑 } } ``` 通过这个工具类,开发者可以方便地调用静态方法进行HTTP请求,而不必关心底层实现的细节。 总结起来,...

    java中发送http包,包含get及post请求

    HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Response: " + response.body()); } } ``` 6. **安全与优化** 在实际项目中,确保...

    Java Http发起get和post请求

    可能的实现包括静态方法,如`sendGetRequest`和`sendPostRequest`,它们接收URL和参数作为输入,返回响应结果。这样的工具类可以避免代码重复,提高代码复用性。 总之,Java中发起HTTP GET和POST请求有多种方式,...

    java http post和get请求回调

    这里的`sendPostRequest()`方法应返回请求的响应,`Consumer<String>`是回调接口,它会在请求完成后接收并处理响应数据。 同样,`HttpRequest.java`和`HttpRevMsg.java`可能是自定义的类,用于封装HTTP请求和响应。...

    java发http请求(post&get)

    public void sendPostRequest() throws IOException { RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), "param1=value1&param2=value2"); Request request = new...

    webservice调用实例,通过HttpClient调用

    public static String sendPostRequest(String url, Map, String> params) throws Exception { // ... HttpPost httpPost = new HttpPost(url); List<NameValuePair> nameValuePairs = new ArrayList(); for ...

    httpClient请求

    2. **执行HTTP请求**:工具类会提供如`sendGetRequest()`和`sendPostRequest()`等方法,接受URL和请求参数作为输入,返回HTTP响应。 3. **处理响应**:包括读取响应状态码、获取响应体、解析JSON或XML数据等。可能...

    HttpClientUtils

    4. 调用工具类提供的方法执行请求,例如`sendPostRequest()`或`sendGetRequest()`。 5. 处理返回的响应,获取响应体、状态码等信息。 6. 如果涉及到JSON交互,可以使用工具类提供的方法将响应体转化为Java对象。 ...

    httpclient4.3工具类

    在实际使用`httpclientUtils`时,开发者可以通过调用工具类提供的方法,如`sendGetRequest(String url)`、`sendPostRequest(String url, Map, String> params)`等,轻松地发起HTTP请求并获取响应。这些方法通常会...

    HttpClient.php

    HttpClient.class.php 文件是一个基于 PHP 的 HTTP 客户端类,用于模拟 HTTP 的 GET 和 POST 请求。在 Web 开发中,这种功能通常用于自动化测试、数据抓取或者与远程 API 进行交互。HttpClient 类提供了简单易用的...

Global site tag (gtag.js) - Google Analytics