关于 HttpURLConnection POST请求 上传 以及中文乱码问题

最近项目中加了一个上传需求 用了几个框架发现跟后台总是不搭接 于是乎 还是用 HttpURLConnection 但是也碰到了许多坑

框架用多了 忘记了首先需要开启一个子线程 new Thread();\

以下为集中POST请求方式

POST 表单请求

  1. public String posts(String url, < Map String >, String form) {
    HttpURLConnection conn = null;
    PrintWriter pw = null;
    BufferedReader rd = null;
    StringBuilder out = new StringBuilder();
    StringBuilder sb = new StringBuilder();
    String line = null;
    String response = null;
    for (String key : form.keySet()) {
    if (out.length() != 0) {
    out.append(“&”);
    }
    out.append(key).append(“=”).append(form.get(key));
    }
    try {
    conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(“POST”);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setReadTimeout(20000);
    conn.setConnectTimeout(20000);
    conn.setUseCaches(false);
    conn.setRequestProperty(“Content-Type”,
    “application/x-www-form-urlencoded”);
    conn.connect();
    pw = new PrintWriter(conn.getOutputStream());
    pw.print(out.toString());
    pw.flush();
    rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), “UTF-8”));
    while ((line = rd.readLine()) != null) {
    sb.append(line);
    }
    response = sb.toString();
    } catch (MalformedURLException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    if (pw != null) {
    pw.close();
    }
    if (rd != null) {
    rd.close();
    }
    if (conn != null) {
    conn.disconnect();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    return response;
    }

POST JSON请求

  1. //post字符串请求 没用到
    public String post(String url, String rawBody) {
    HttpURLConnection conn = null;
    PrintWriter pw = null;
    BufferedReader rd = null;
    StringBuilder sb = new StringBuilder();
    String line = null;
    String response = null;
    try {
    conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(“POST”);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setReadTimeout(20000);
    conn.setConnectTimeout(20000);
    conn.setRequestProperty(“Content-Type”,
    “application/x-www-form-urlencoded”);
    conn.setUseCaches(false);
    conn.connect();
    pw = new PrintWriter(conn.getOutputStream());
    pw.print(rawBody);
    pw.flush();
    rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), “UTF-8”));
    while ((line = rd.readLine()) != null) {
    sb.append(line);
    }
    response = sb.toString();
    } catch (MalformedURLException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    if (pw != null) {
    pw.close();
    }
    if (rd != null) {
    rd.close();
    }
    if (conn != null) {
    conn.disconnect();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    return response;
    }
    上传文件

    private void upLoadByCommonPost(String path) {

    String end = "\r\n";
    String twoHyphens = "--";
    String boundary = "******";
    try {
        URL url = new URL(uploadUrl);
        HttpURLConnection httpURLConnection = null;
        httpURLConnection = (HttpURLConnection) url
                .openConnection();
        httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K
        // 允许输入输出流
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setUseCaches(false);
        // 使用POST方法
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        httpURLConnection.setRequestProperty("Charset", "UTF-8");
        httpURLConnection.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);
        DataOutputStream dos = new DataOutputStream(
                httpURLConnection.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + end);
        dos.writeBytes("Content-Disposition: form-data; name=\"multipartFile\"; filename=\""
                + path.substring(path.lastIndexOf("/") + 1) + "\"" + end);
        dos.writeBytes(end);
        FileInputStream fis = new FileInputStream(path);
        byte[] buffer = new byte[8192]; // 8k
        int count = 0;
        // 读取文件
        while ((count = fis.read(buffer)) != -1) {
            dos.write(buffer, 0, count);
        }
        fis.close();
        dos.writeBytes(end);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
        dos.flush();
        InputStream is = httpURLConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, "utf-8");
        BufferedReader br = new BufferedReader(isr);
        String result = br.readLine();
        Log.i("--superme:ok>>", result);
        dos.close();
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
        Log.i("--superme:no>>", e.getMessage());
    }
    

    }

上边的这种有时候可能出现乱码 那么 还有下边

  1. private void upLoadFilePost(String path) {

    ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
    HttpClient client = new DefaultHttpClient();// 开启一个客户端 HTTP 请求
    HttpPost post = new HttpPost(uploadUrl);//创建 HTTP POST 请求
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(Charset.forName(HTTP.UTF_8));//设置请求的编码格式
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
    builder.addBinaryBody("multipartFile", new File(path));
    StringBody stringBody = new StringBody("中文乱码", contentType);
    builder.addPart("test", stringBody);
    HttpEntity entity = builder.build();// 生成 HTTP POST 实体
    post.setEntity(entity);//设置请求参数
    HttpResponse response = null;// 发起请求 并返回请求的响应
    try {
        response = client.execute(post);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (response.getStatusLine().getStatusCode() == 200) {
    }
    

    }

以上只是我个人用到的 具体里边的一些参数设置 用到时候 在去查看就好

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值