在Java中使用Get/Post方式发送Http请求

在Java中使用Get/Post方式发送Http请求

RESTfulClient工具类:

package com.fsc.civet.mongo.util;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

public class RESTfulClient {
    
    public static String SERVER_URL = "";
    public static String REQUEST_PATH = "";
    public static String REQUEST_URL = SERVER_URL + REQUEST_PATH;
    public static String GET_CONTENT_TYPE = "application/json";
    public static String GET_ACCEPT = "application/json";
    public static String GET_CHARSET = "UTF-8";
    
    public static String PUT_CONTENT_TYPE = "text/plain";
    public static String PUT_ACCEPT = "application/json";
    public static String PUT_CHARSET = "UTF-8";
    
    public static String POST_CONTENT_TYPE = "application/json";
    public static String POST_ACCEPT = "application/json";
    public static String POST_CHARSET = "UTF-8";

    public static String executeGet(String path)
            throws HttpHostConnectException, IOException {
        String fullPath = SERVER_URL + path;
        HttpGet httpQuery = new HttpGet(fullPath);
        httpQuery.addHeader("Accept", "text/plain;charset=UTF-8");// );
        httpQuery.addHeader("Accept", "application/json");
        return doRequest(httpQuery);

    }
    
    public static String executePost(String path, String body)
            throws IOException {
        HttpPost httpQuery = new HttpPost(SERVER_URL + path);
        System.out.println("request Path : " + SERVER_URL + path);
        httpQuery.addHeader("Content-Type", POST_CONTENT_TYPE);
        httpQuery.addHeader("Accept", POST_ACCEPT);
        httpQuery.addHeader("charset", POST_CHARSET);
        if (null != body) {
            StringEntity se = new StringEntity(body);
            httpQuery.setEntity(se);
        }
        return doRequest(httpQuery);
    }
    
    public static String executePost1(String path, List<NameValuePair> params) throws IOException {
        HttpPost httpQuery = new HttpPost(SERVER_URL + path);
        System.out.println("request Path : " + SERVER_URL + path);
        httpQuery.addHeader("Content-Type", POST_CONTENT_TYPE);
        httpQuery.addHeader("Accept", POST_ACCEPT);
        httpQuery.addHeader("charset", POST_CHARSET);
        if (null != params) {
            httpQuery.setEntity(new UrlEncodedFormEntity(params));
        }
        return doRequest(httpQuery);
    }

    public static String executePut(String path, String body)
            throws IOException {
        HttpPut httpQuery = new HttpPut(SERVER_URL + path);
        httpQuery.addHeader("Content-Type", PUT_CONTENT_TYPE);
        httpQuery.addHeader("charset", PUT_CHARSET);
        if (null != body) {
            StringEntity se = new StringEntity(body, PUT_CHARSET);
            httpQuery.setEntity(se);
        }
        return doRequest(httpQuery);
    }
    
    public static String executePutTwo(String path, String body)
            throws IOException {
        HttpPut httpQuery = new HttpPut(SERVER_URL + path);
        httpQuery.addHeader("Content-Type", PUT_ACCEPT);
        httpQuery.addHeader("charset", PUT_CHARSET);
        if (null != body) {
            StringEntity se = new StringEntity(body, PUT_CHARSET);
            httpQuery.setEntity(se);
        }
        return doRequest(httpQuery);
    }


    private static String doRequest(HttpRequestBase httpQuery)
            throws ParseException, IOException, HttpHostConnectException {
        String content = null;
        final HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
        HttpResponse httpResponse = httpClient.execute(httpQuery);
        HttpEntity entity = null;
        entity = httpResponse.getEntity();

        if (null != entity) {
            content = EntityUtils.toString(entity, HTTP.UTF_8);
        }

        return content;
    }
    public static String executePostNew(String type, File file, String url, String username) throws Exception {
        //new一個MultipartEntityBuilder封裝類的對象,并設定模式及編碼類型
        MultipartEntityBuilder mulEnBuilder = MultipartEntityBuilder.create();
        mulEnBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        mulEnBuilder.setCharset(Charset.forName("UTF-8"));
        //封裝文本內容

        mulEnBuilder.addTextBody("username", username, ContentType.create(type, Charset.forName("UTF-8")));
        //封裝二進制文件
        mulEnBuilder.addBinaryBody("file", file, ContentType.create("application/octet-stream", Charset.forName("UTF-8")), file.getPath());
        //new一個HttpEntity封裝類的對象,并將上面的MultipartEntityBuilder封裝類的對象封裝進該HttpEntity對象
        HttpEntity httpEntity = mulEnBuilder.build();
        //new一個指定URL的HttpPost對象,并將上面的MultipartEntityBuilder封裝類封裝進該HttpPost對象
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(httpEntity);
        return doRequest(httpPost);
    }
    
    public static String executePostNew1(String type, File file, String url, String username,String user) throws Exception {
        //new一個MultipartEntityBuilder封裝類的對象,并設定模式及編碼類型
        MultipartEntityBuilder mulEnBuilder = MultipartEntityBuilder.create();
        mulEnBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        mulEnBuilder.setCharset(Charset.forName("UTF-8"));
        //封裝文本內容
        mulEnBuilder.addTextBody("username", username, ContentType.create(type, Charset.forName("UTF-8")));
        mulEnBuilder.addTextBody("admin", user, ContentType.create(type, Charset.forName("UTF-8")));

        //封裝二進制文件
        mulEnBuilder.addBinaryBody("file", file, ContentType.create("application/octet-stream", Charset.forName("UTF-8")), file.getPath());
        //new一個HttpEntity封裝類的對象,并將上面的MultipartEntityBuilder封裝類的對象封裝進該HttpEntity對象
        HttpEntity httpEntity = mulEnBuilder.build();
        //new一個指定URL的HttpPost對象,并將上面的MultipartEntityBuilder封裝類封裝進該HttpPost對象
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(httpEntity);
        return doRequest(httpPost);
    }
    
    public static String executePostTwo(String url, String username, String imgPath) throws Exception {

        HttpPost httpPost = new HttpPost(url);
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        //传递2个参数  name和password
        nvps.add(new BasicNameValuePair("username", username));
        nvps.add(new BasicNameValuePair("imgPath", imgPath));
        HttpEntity reqEntity = new UrlEncodedFormEntity(nvps,Consts.UTF_8);
        httpPost.setEntity(reqEntity);
        return doRequest(httpPost);
    }
    
//  public static String executePostTwo(String type, String url, String username, String imgPath) throws Exception {
//      //new一個MultipartEntityBuilder封裝類的對象,并設定模式及編碼類型
//      MultipartEntityBuilder mulEnBuilder = MultipartEntityBuilder.create();
//      mulEnBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//      mulEnBuilder.setCharset(Charset.forName("UTF-8"));
//      //封裝文本內容
//
//      mulEnBuilder.addTextBody("username", username, ContentType.create(type, Charset.forName("UTF-8")));
//      mulEnBuilder.addTextBody("imgPath", imgPath, ContentType.create(type, Charset.forName("UTF-8")));
//
//      //new一個HttpEntity封裝類的對象,并將上面的MultipartEntityBuilder封裝類的對象封裝進該HttpEntity對象
//      HttpEntity httpEntity = mulEnBuilder.build();
//      //new一個指定URL的HttpPost對象,并將上面的MultipartEntityBuilder封裝類封裝進該HttpPost對象
//      HttpPost httpPost = new HttpPost(url);
//      httpPost.setEntity(httpEntity);
//      return doRequest(httpPost);
//  }

}

调用:

public static String demo(String username,String createBy,File file) {

        JsonResponse result = new JsonResponse();
        
        // 将头像存入临时文件中
        if (file == null) {
            return "";
        } else {    
            try {
                String type = "text/plain";
                // 读取url配置文件
                String url = Props.getString("upload.url");//存储访问的url
                String res = RESTfulClient.executePostNew1(type, file, url, username, createBy);
                return res;
            } catch (Exception e) {
                return e.getMessage();
            }
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,120评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,341评论 25 709
  • 这次聚会,我们来看一本书,《这样读书就够了》,主要讲的是成年人读书的困难,以及一种新的读书观念。 我读书的困难是什...
    逾越期Paul阅读 1,589评论 0 0
  • 高平三中364班毕澜澜 不知不觉我已经开学4天了,开学时的情景却在我的脑海里挥之不去,回顾这4天,我学到...
    炎帝故里阅读 2,738评论 0 0
  • 是黄色的嫩黄嫩黄坐在山坡上在那个湖边 小房子没有窗户没有门呆呆得坐在山坡上在那个湖边 只有吃草的小羊过来偎了偎 还...
    葺宝阅读 1,225评论 0 1

友情链接更多精彩内容