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

来源:互联网 发布:k歌达人 网络异常 编辑:程序博客网 时间:2024/06/05 13:17

最近项目中加了一个上传需求 用了几个框架发现跟后台总是不搭接 于是乎 还是用 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
原创粉丝点击