`

appache read and write stream

    博客分类:
  • work
阅读更多

package com.cn.sevlet;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.UnknownServiceException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;

public class ClientBuilder {
private static final String CHARSET = "utf-8";
@SuppressWarnings("null")
public static String request(Context context, String uri,
UnamParameters param, String httpMethod) throws UnsupportedEncodingException, IllegalStateException, IOException {
String result = null;
HttpClient client = new DefaultHttpClient();


if (httpMethod.equalsIgnoreCase("get")) {
BufferedReader reader = null;
HttpGet get = new HttpGet(uri);
HttpResponse response = client.execute(get);
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), CHARSET));//地址

StringBuffer sb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
result = sb.toString();
return result;
} 
else if (httpMethod.equalsIgnoreCase("post")) {
final String MULTIPART_FORM_DATA = "multipart/form-data";
final String BOUNDARY = "infovillage";//分隔符
final String TWO_HYPHENS = "--";
final String ENDLINE = System.getProperty("line.separator");

Map<String, String> table = new HashMap<String, String>();
table.put("product", param.getProduct());
table.put("price", param.getPrice());
table.put("unit", param.getUnit());
table.put("name", param.getName());
table.put("telephone", param.getTelephone());
table.put("address", param.getAddress());
table.put("description", param.getDescription());

StringBuffer sb = new StringBuffer();
Set<Map.Entry<String, String>> set = table.entrySet();
/*文件内容为二进制流的形式*/
for (Map.Entry<String, String> entry : set) {
sb.append(TWO_HYPHENS + BOUNDARY + ENDLINE);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + ENDLINE);
sb.append(ENDLINE);
sb.append(entry.getValue() + ENDLINE);
}
sb.append(TWO_HYPHENS + BOUNDARY + ENDLINE);
sb.append("Content-Disposition: form-data; name=\"picture\"; filename=\"uploadImage.jpg\"" + ENDLINE);
sb.append("Content-Type: image/jpeg" + ENDLINE);
sb.append(ENDLINE);
sb.append(param.getPicture());
sb.append(ENDLINE);
sb.append(TWO_HYPHENS + BOUNDARY + TWO_HYPHENS +ENDLINE);

HttpPost post = new HttpPost(uri);
post.addHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
DataOutputStream output=null;
try{
output.writeBytes(sb.toString());
}catch(IOException e){
e.printStackTrace();
}
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
swapStream.writeTo(output); 
byte []bytes= swapStream.toByteArray();
InputStream in = new ByteArrayInputStream(bytes); 
output.flush();


post.setEntity(new InputStreamEntity(in, bytes.length));
// System.out.println(sb.toString());
HttpResponse response = client.execute(post);

BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer strbuf = new StringBuffer();
String line = null;
while((line = reader.readLine()) != null) {
strbuf.append(line);
}
result = strbuf.toString();
reader.close();
}
return result;
}
public static InputStream getFile(Context context, String uri,
UnamParameters param, String httpMethod)
throws UnknownServiceException {
InputStream is = null;
if (httpMethod.equalsIgnoreCase("GET")) {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(uri);
try {
HttpResponse response = client.execute(get);
is = response.getEntity().getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return is;
}
 
分享到:
评论

相关推荐

    apache compress src

    Apache Commons Compress库中的BZip2Stream和BZip2Compressor类提供了与BZ2文件交互的能力。通过这些类,我们可以读取BZ2压缩文件的内容,也可以将数据压缩成BZ2格式。例如,我们可以使用BZip2...

    write-read-csv-files-in-java-example-code.zip_read csv java

    在Java中,我们可以使用内置的`BufferedReader`类配合`split()`方法来读取CSV文件,但更常见的是使用第三方库如Apache Commons CSV或OpenCSV。以下是一个使用Apache Commons CSV库的示例: ```java import org....

    apacheservlet文件上传与下载

    response.getOutputStream().write(buffer, 0, length); } } catch (IOException e) { // 处理异常 } ``` 4. 关闭流:确保所有的输入/输出流在操作完成后都被正确关闭。 总结,Apache Servlet 提供了处理HTTP...

    PHP生成和在线浏览类库.zip

    define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE','w b'); // truncates existing file data, use with care define('FOPEN_WRITE_CREATE','ab'); define('FOPEN_READ_WRITE_CREATE','a b'); define('FOPEN...

    深入讲解PHP线程并发种类

    $ready_streams = stream_select($read_streams, $write_streams, $except_streams, $timeout); if ($ready_streams === false) { echo "Error occurred during stream selection.\n"; break; } elseif ($ready...

    commons-fileupload上传和下载例子.zip

    response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); try (InputStream in = new FileInputStream(fileToDownload);...

    java 操作word文档

    din.read(tableStream); din.close(); // ... 处理表格中的文本 ... StringBuffer sb = new StringBuffer(); for (int x = 0; x (); x++) { WordTextPiece nextPiece = (WordTextPiece) text.get(x); sb....

    使用Flink和Pulsar进行批流一体弹性计算.pdf

    1. **写与追尾读(Write & Tailing Read)**:生产者将消息写入Pulsar,消费者则从消息的末尾开始读取,即所谓的“追尾读”。这种方式适用于实时性要求较高的场景,例如实时数据分析或监控系统等。 2. **追赶读与...

    java实现的PDF与JPG文件互转

    ImageIO.write(image, "JPEG", new File("D:/output_" + page + ".jpg")); } document.close(); ``` 2. **JPG转PDF**: 对于JPG到PDF的转换,我们可以使用Java的ImageIO类读取JPG图片,然后利用PDFBox创建一个...

    JAVA poi 做EXCEL导出(包含图片) 完整版

    imageStream.read(imageData); imageStream.close(); ``` 接下来,创建一个`Picture`对象,并将其添加到`Drawing`对象中: ```java import org.apache.poi.ss.usermodel.Picture; import org.apache.poi.xssf....

    java文件上传和下载案例

    while ((length = in.read(buffer)) &gt; 0) { out.write(buffer, 0, length); } } ``` 这里的关键在于设置正确的MIME类型(`application/octet-stream`),以及在响应头中添加`Content-Disposition`来指定文件名,...

    Java抓取网页内容三种方式

    out.write(buffer, 0, bytes_read); } catch (Exception e) { System.err.println(e); System.err.println("Usage: java GetURL &lt;URL&gt; []"); } finally { // 无论如何都要关闭流 try { in.close(); out....

    hudi learning.pdf

    Apache Hudi 学习指南 Apache Hudi 是一个开源的数据管理系统,旨在处理大规模的分析数据集。它提供了流式处理能力,能够实时...5. Read / Write Optimized:Hudi 可以根据实际情况优化读写操作,提高数据处理效率。

    计算机网络第六版答案

    These well-established and time-honored rules have made it easier for nations and people to live and work together. Part of protocol has always been the acknowledgment of the hierarchical standing of...

    jsp文件的上传和下载

    os.write(buffer, 0, read); } os.flush(); os.close(); bis.close(); fis.close(); ``` 在实际项目中,为了保证文件安全性和性能,通常会结合使用这些方法。例如,对于小文件,可以使用直接输出的方式;对于大...

    java实现生成ppt文件

    imageStream.read(imageData); imageStream.close(); XSSFPictureData pictureData = ppt.addPicture(imageData, XSLFRelation.PICTURE.getType()); XDDFShape pictureShape = slide.createDrawingPatriarch()....

    jsp+servlet实现文件上传与下载功能.docx

    while ((length = fis.read(buffer)) != -1) { response.getOutputStream().write(buffer, 0, length); } fis.close(); } else { response.getWriter().write("文件不存在!"); } } } ``` 在这个例子中,...

    Struts实现文件的上传下载

    os.write(buffer, 0, read); } os.close(); is.close(); // 处理成功后的逻辑,如跳转到成功页面 return mapping.findForward("success"); } } ``` 4. **文件下载**: 文件下载通常涉及到生成HTTP响应,...

Global site tag (gtag.js) - Google Analytics